devxlogo

Access Specification of a Virtual Method Should not Change in a Derived Class

Access Specification of a Virtual Method Should not Change in a Derived Class

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

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.

devx-admin

Share the Post: