Environment: VS2010
Question: Exploring access to C ++ private inheritance from the outside
Code:
# Include <iostream>
Using namespace std;
Class
{
Public:
A (){
A = 0;
Cout <"A: A ()" <endl;
}
Int;
};
Class B: protected
{
Public:
B (){
I = 1;
Cout <"B: B ()" <endl;
}
Public:
Int I;
};
Int main (void ){
B b2;
B2. I = 20;
A * pp = & b2;
Cout <"pp-> a:" <pp-> a <"" <"b2. I" <b2. I <endl;
Return 0;
}
A * pp = & b2; error: // error C2243: "type conversion": conversion from "B *" to "A *" exists, but cannot be accessed
That is, the pointer to the base class can be converted to a derived class, but it cannot be accessed because it is a protected inheritance.
Change A * pp = & b2; To A * pp = (A *) & b2; that is, convert the pointer pointing to the derived class to A base class pointer for access.
The effect is as follows:
Add the following code to Class B:
Void SetB (int n ){
This-> a = n;
}
In this way, you can also modify a of the base class.
Although it can be accessed, it is not recommended to forcibly convert the pointer pointing to a derived class to a base class pointer because it violates the principle of protection inheritance.
Note: The forced conversion of C ++ is very powerful, and it does not check the type.
Author Wentasy