C ++ resets the access of members

Source: Internet
Author: User

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;

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.