In the past, I did not pay much attention to the reference subclass or base class pointer pointing to the subclass in C ++ inheritance. Now, write a small program to test this result.
// Testcpp. cpp: defines the entry point for the console application.
# Include "stdafx. H"
# Include "iostream"
Using namespace STD;
Class B
{
Public:
Virtual void print ()
{
Cout <"This is B" <Endl;
}
};
Class A: Public B // Class A inherits Class B
{
Public:
Virtual void print ()
{
Cout <"this is a" <Endl;
}
};
Int _ tmain (INT argc, _ tchar * argv [])
{
A;
B;
B & b1 = A; // base class reference subclass
B * pb = & A; // The base class Pointer Points to the subclass.
Cout <"A. Print ():";
A. Print ();
Cout <"B. Print ():";
B. Print ();
B =;
Cout <"B = a B. Print :";
B. Print ();
Cout <"b1.print ():";
B1.print ();
Cout <"Pb-> Print ():";
Pb-> Print ();
Getchar ();
Return 0;
}
The output result is as follows:
A. Print (): This is
B. Print (): This is B
B = a B. Print: This is B
B1.print (): This is
Pb-> Print (): This is
First, I start from inheritance, because a inherits B. For example:
Note: The virtual function pointer is a hidden member variable. This Hidden variable does not change in the copy constructor.
Analyze the following statements:
B = A; // use object A to construct function B. In this process, only the copy constructor is called to assign values to data members, therefore, the virtual function pointer of object B still points to the virtual function of object B.
Cout <"B = AB. Print :";
B. Print (); // B = a B. Print: This is B
Cout <"b1.print ():"; // B1 is a reference, that is, another name of the memory address of object A. Therefore, B1 points to the memory address of object.
B1.print (); // b1.print (): This is
Cout <"Pb-> Print ():"; // the pointer actually stores the address of another memory in the memory. To put it bluntly, it is also a variable, this variable is special, that is, the Pb variable stores the address of the memory of object,
Pb-> Print (); // This Is