I have a doubt regarding, the accessibility of the private member functions of a derived class, which is an overridden form of a public and virtual function in its base class.
I would like to display by problem in the followin code snippet.
class Base
{ public:
virtual void print()
{
cout<<"In the virtual print method of Base class";
}
};
class Derived: public Base
{ private:
virtual void print()
{
cout<<"In the virtual print method of Derived class";
}
};
int main()
{ Base *ptr = new Derived();
ptr->print();
return 0;
}
Output:
When run,the output is as follows
"In the virtual test method of Derived class",
but the print function in the 'Derived' class is marked as private.
Looking for an Explanation for this.
A similar code in Java would have given a Compile time error, but in C++ it neither gives any compile time error, nor a runtime exception.
It runs just fine.
Member access is checked at compile time, virtual function calls are determined at run time. The compiler has no way of knowing that ptr->print() resolves to a private function.