Class A contains class B instances. When Class B's member functions are executed, the address of Class A is dynamically obtained.

Source: Internet
Author: User

When looking at <com essence>, there is a small problem: if Class A contains class B instances, Class A dynamically obtains the address of Class A when class B's member functions are executed.

After thinking for a while, I wrote the instance Code as follows:

Class Croom
{
Public:

Class bed
{
Public:
Int m_member1;
Int m_member2;
};

Class door
{
Public:
Int m_member1;

Void open ()
{
Cout <"open operation" <Endl;
}

Int getparentclsthispointer ()
{
Croom * plobj = NULL;

Int lioffset = reinterpret_cast <int> (& plobj-> mdoor); // obtains the offset of A Class door instance in a Croom instance.
Int liparentclsthispointer = reinterpret_cast <int> (this)-lioffset; // obtain the address of the Croom instance.

Return liparentclsthispointer;
};

};

Bed mbed;
Door mdoor;
};

Class Croom contains an instance of the door class.GetparentclsthispointerDynamically obtain the address of the class Croom instance.

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.