Private virtual function in a derived class

Possible duplicate:
C ++: overriding public \ private inheritance

class base { public: virtual void doSomething() = 0; }; class derived : public base { private: // <-- Note this is private virtual void doSomething() { cout << "Derived fn" << endl; } }; 

Now, if I do the following:

 base *b = new child; b->doSomething(); // Calls the derived class function even though that is private 

Question:

  • It is able to call a derived function of a class, even if it is private. How is this possible?

Now, if I change the inheritance access specifier from public to protected / private, I get a compilation error:

 'type cast' : conversion from 'Derived *' to 'base *' exists, but is inaccessible 

Note. I know the concepts of inheritance access specifiers. So in the second case, since it got private / protected, it is not available. But I wonder about the answer to the first question. Any input would be appreciated.

+6
source share
3 answers

Access control is implemented at compile time, and not at run time, and polymorphism (including the use of virtual functions) is a run-time function.

+6
source

In the first case, an access check is performed (as always) for the static type with which the call is made. The static type *b is base , in which case doSomething() is public .

C ++ 03 11.6 "Access to virtual functions" says:

The access rules (Article 11) for a virtual function are determined by its declaration and are not affected by the rules for the function, which then overrides it. [Example:

 class B { public: virtual int f(); }; class D : public B { private: int f(); }; void f() { D d; B* pb = &d; D* pd = &d; pb->f(); //OK:B::f()is public, // D::f() is invoked pd->f(); //error:D::f()is private } 

-end example]

Access is checked at the dial peer using the type of expression used to indicate the object for which the member function is called (B * in the above example). Access to the member function in the class in which it was defined (D in the above example) is not known at all.

Keep in mind that "access to the member function in the class in which it was defined (D in the above example) is not known at all." In general, at the point in your example where b->doSomething(); is called b->doSomething(); , the compiler may not be aware of derived (or child ) at all, and even more so whether access to derived::doSomething() private.

+6
source

Private functions must be hidden from the outside world and from derived classes. Although you override the parent specifier of the parent DoSomething and make it private, you create a base class; therefore, in the first case, you can call the basic DoSomething, since it is publicly available. This script can be used if you want to stop people getting a derived class.

In the second case, the private access specifier forces the base elements not to be exposed to users of the derived class, which actually makes the derived class useless.

0
source

All Articles