C ++ has the following inheritance features:ProgramBut it is not uncommon for large projects. Most beginners, or those who do not often use the C ++ inheritance feature, will think that the Members in the derived class cannot have the same name as the members in the base class (except for virtual functions, this situation is not only acceptable, but also common.
Assume that there are two classes, one is a list class and one is a string class. The list class contains the insert () function and the X variable, and the insert () function is not a virtual function, and the string inherits
In list, and there are also insert () Functions and X variables. In this case, we call the insert () function through the string object or directly call the X variable.
String: insert () or access string: X. How can we access members in the base class? Most C ++ introductory books do not have an explanation of this issue.
To solve this problem, let's take a look at the memory structure of C ++ class objects.
The image is from the network. Note: __vfptr is a virtual function pointer.
The figure shows the memory structure of the derived class. before the members of the derived class, there will be a piece of memory to store the members of the base class. We need to call the list: insert () and list :: X is stored here.
String class structure:
List: insert
List: x
String: insert
String: x
In this way, it is much easier to access the duplicate members in the base class. Since the base class members are in the object header, we can use the forced type conversion method to access the members according to the format of the base class (for this, we have seen peviewerSource codeYou must be familiar with it. peviewer reads attributes after converting the memory that stores the file content ).
DetailsCode:
String STR;
(List *) (& Str)-> insert (); // access list: insert ()
(* (List *) (& Str). insert ();
(List *) (& Str)-> X; // access list: x
(* (List *) (& Str). X;