Conversion of UPCASET and DOWNCAST types in C ++

Source: Internet
Author: User

Example:

Class

{

Int ai;

};

Class C

{

Int ci;

};

Class B: public A, public C

{

Int bi;

};

Int _ tmain (int argc, _ TCHAR * argv [])

{

B B;

A * pa = & B;

C * pc = & B;

Return 0;

}



We can see that pa points to the address of A sub-object in B, while pc points to the address of C sub-object in B.

Let's look at the reverse situation:

In Main ()

A;

A a_tmp;

C c;

A. ai = 3;

A_tmp.ai = 4;

C. ci = 5;

B * pba = static_cast <B *> (& a); // you must use static_cast or force conversion. Otherwise, compilation fails.

B * pbc = static_cast <B *> (& c); // same

Return 0;

}



We can see that after the forced conversion, the C sub-object in pba actually points to a_tmp, so down_cast conversion is not safe.

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.