I came across this question while experimenting with following simple code.
#include <iostream>
using namespace std;
class A{
public:
A(){ cout << "Def contr A" << endl; }
~A(){ cout << "Def destr A" << endl; }
};
class B : protected A{
public:
B(){ cout << "Def contr B" << endl;}
~B(){ cout << "Def destr B" << endl; }
};
int main() {
A* a_p = new B();
return 0;
}
I got following error
error: 'A' is an inaccessible base of 'B'
By referring this & this , I found that details of base class A are not visible outside of class scope of B and B* is implicitly casted into a A*.
But my question is, compiler already knows the definition and layout of A. Why it is giving an error.
My assumption is, even though compiler knows the definition of A, it doesn't know it is safe to cast B* into A* since inherited data is not visible.
Can someone help me to understand what really happens here?
Just to make the question more clear, Lets say we have another class C which is not inheriting from A.
Then I can easily do A* a = (A*) new C(); this without an error.
Why this is allowed and why A* a_p = new B(); is not allowed? What is the difference between these two scenarios?