Please take a look at the code snippet given below:#include<iostream>
using namespace std;
class A
{
public:
virtual void test(){cout<<"Default implementation called"<<endl;}
};
class B:public A
{
private:
void test(){cout<<"Derived class called"<<endl;}
};
int main()
{
A *a = new B;
a->test();
return 1;
}
The output is :
Derived class called
Now, my question is how can I access a private function of a class from
main? I accept that I did it via dynamic polymorphism. Still, should I
be allowed to access a member function which is private?
There are two answers for your question. One is how the method gets
called? The accesibility of a method is defined through the static type
of the pointer used for calling the method. So in your case, since the
dynamic type of 'A* a' is 'B' and static type is 'A'. The static type
'A' is used to define the accesibility of the method. And hence this
call is perfectly legal.
Should it be allowed or is it breaking encapsulation? The answer to this
question is that when you derive your class from 'A' you are actually
abiding by the constraints of 'A'. If you dont want your method to be
visible outside why are you overloading the same method defined in 'A'.
You can anyway create a new method name and can do your job. When you
are overloading a method from 'A', you are actually want to overload
test() and want to use the polymorphism.
So, from language point of view this is justified. It is a design
issue. You should avoid overloading the test() method if you dont want
it to be called.
-Shantanu Garg