You are right that in order to redefine a function in a derived class, it must inherit it from the base class (in addition, the function of the base class must be virtual). However, you are mistaken in your assumption that virtual functions are not inherited. For example, the following works well (and is actually a well-known idiom for checking for a precondition / postcondition):
class Base { public: void operate_on(some thing); private: virtual void do_operate_on(some thing) = 0; }; void Base::operate_on(some thing) {
The way to see if private methods are really inherited is to look at the error messages generated by the following code:
class Base { private: void private_method_of_B(); }; class Derived: public Base { }; int main() { Derived d; d.private_method_of_B(); d.method_that_does_not_exist(); }
Attempting to compile this with g ++ results in the following error messages:
privatemethodinheritance.cc: In function 'int main()': privatemethodinheritance.cc:4: error: 'void Base::private_method_of_B()' is private privatemethodinheritance.cc:15: error: within this context privatemethodinheritance.cc:16: error: 'class Derived' has no member named 'method_that_does_not_exist'
If the Derived class does not inherit this function, the error message will be the same in both cases.
source share