Instance parsing C + + virtual table

Source: Internet
Author: User

Os:windows 7

Keywords: vs2012,c++,vtable, virtual table

1. Create a WIN32 console application code as follows:

#include"stdafx.h"#include<string>#include<iostream>classa{ Public:    VirtualSTD::stringAName () {return "A";}};classb{ Public:    VirtualSTD::stringBname () {return "B";}};classE | PublicA Publicb{ Public:    VirtualSTD::stringBname () {return "C";}};int_tmain (intARGC, _tchar*argv[]) {C* PC =NewC (); C* PC1 =NewC (); Std::cout<<pc->bname () <<Std::endl; B* PB = static_cast<b*>(PC); Std::cout<<pb->bname () <<Std::endl; //A * PA = static_cast<a*> (PB);A * PA = dynamic_cast<a*>(PB); Std::cout<<pa->aname () <<Std::endl; A* PA1 = reinterpret_cast<a*>(PB); Std::cout<<pa1->aname () <<Std::endl; return 0;}

2. Compile and run, the console output is as follows:

C

C

A

C

Do you have any strange places to see this result? Why is the "pa1->aname ()" Output C?

3. The virtual table structure seen in the Watch Window is as follows:

Summarized as follows:

    • PCs and pC1 are two instance pointers to Class C, and the virtual tables of the two instances are the same, meaning that the virtual table belongs to the class, and a class has a virtual table.
    • Because Class C overrides the Bname function of Class B, the virtual table of c is stored in C::bname
    • "A * PA = static_cast<a*> (PB);" is not compiled, because A and B are unrelated two classes, that is, there is no inheritance relationship.
    • "A * PA = dynamic_cast<a*> (PB);" Yes, because dynamic_cast will perform type checking at run time, dynamic_cast is the safest, but least efficient.
    • "A * pA1 = reinterpret_cast<a*> (PB);" Can be compiled and passed, but the runtime will have unexpected results. Reinterpret_cast casts a forced type, but does not correct the virtual table.

Instance parsing C + + virtual table

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.