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<<"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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist