Saturday, 23 July 2016

Whether virtual function will be allowed to call when it is placed under the private access specifier?

 
GUESS THE OUTPUT OF THE PROGRAM
 


#include<iostream>
#include<array>

class Fruit
{
	public:
		virtual void getColour()=0;
};

class Apple : public Fruit
{
	private: 
		virtual void getColour()
		{
			std::cout<<"My Colour is red"<<std::endl;
		}
};

int main()
{
	Fruit *anyFruitPtr=new Apple;
	// NOTE getColour is under private section of Apple
	anyFruitPtr->getColour();
	return 0;
}


My Colour is red
Even though getColour is placed under private section of the Apple class it will be allowed to call when it is a virtual function.

So , why compiler can’t show the compiler error?
Checking the access specifier is part of compilation process and not an run time process.

Just take the statement below,

anyFruitPtr->getColour();

At run time, anyFruitPtr variable can hold any class object which is child of Fruit class.  Since compiler was not aware of actual class in the anyFruitPtr variable, it cannot perform the access specifier validation for the virtual function.