The access specification of a public virtual member function defined in a base class, can be changed in a derived class:
class Base {public: virtual void Say() { cout<<"Base";}};class Derived : public Base {private: //access specifier changed; legal but not a very good idea void Say() {cout <<"Derived";} //overriding Base::Say()};
Although this is legal, it will not work as expected when pointers or references are used: A pointer or reference to Base, can also be assigned to any object derived from Base:
Derived d;Base *p = &d;p->Say(); //OK, invokes Derived::Say()
Since the actual binding of a virtual member function is postponed to runtime, the compiler cannot detect that a non-public member function will be called: it assumes that p points to an object of type Base, in which Say() is a public member. Therefore, you should not override the access specification of virtual member function in a derived class.