Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Aug 14, 1998

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 {
		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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date