Hello All,
I was trying to figure out what happens when a derived class declares a virtual function as private. The following is the program that I wrote
#include <iostream>
using namespace std;
class A
{
public:
virtual void func() {
cout<<"A::func called"<<endl;
}
private:
};
class B:public A
{
public:
B()
{
cout<<"B constructor called"<<endl;
}
private:
void func() {
cout<<"B::func called"<<endl;
}
};
int main()
{
A *a = new B();
a->func();
return 0;
}
Surprisingly (for me) the output was B constructor called B::func called Isn't this violating the private access set for that function. Is this the expected behavior? Is this is a standard workaround or loophole? Are access levels bypassed when resolving function calls through the VTABLE?
Any insight in to this behavior would be greatly helpful. Thanks in advance!
--Ashwin
Further it was mentioned that a privately overriding a virtual member would prevent further classes from inheriting it. Even this is having problems. Modifying the above program to include:
class C: public B
{
public:
void func() {
cout<<"C::func called"<<endl;
}
};
and the main test program to:
int main()
{
A *a = new C();
a->func();
return 0;
}
output is: C::func called