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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS