CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Threaded View

  1. #1
    Join Date
    Feb 2009
    Posts
    326

    access specifier of base virtual function

    Hi,

    A is the base class
    B is the derived from class A

    A has a public virtual function f1()
    B has a private virtual function f1()

    B::f1() not accessible using an object of class B however it is accessible through A* (base pointer)

    Questions:
    1) Is this because determining the access specifiers (public, protected, private) are checked by the compiler at compile time and which virtual function is to be invoked is decided runtime ?
    2) Is this a bug ? (I am using gcc 4.2.1)

    Pasted below is the code:
    Code:
    #include <iostream>
    
    class A
    {
        public:
            virtual void f1() { std :: cout << "A::f1()\n"; }
    };
    
    class B : public A
    {
        private:
            virtual void f1() { std :: cout << "B::f1()\n"; }
    };
    
    int main()
    {
        A a1;
        B b1;
    
        a1.f1();
        //b1.f1(); //Can't access through the object - As expected, this line throws compilation error
    
        //Accessing f1() through base pointer
        A* aPtr = &b1;
        aPtr -> f1(); //Able to access B::f1() though B::f1() is private
    
        return(0);
    }
    Last edited by Muthuveerappan; July 9th, 2011 at 08:08 AM. Reason: explaining the question

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured