C + + class inheritance-small note

Source: Internet
Author: User

classa{ Public: A () {print1 ();}//The call to virtual function inside the constructor itself is not correct, this is only for testing    Virtual voidprint1 () {std::cout<<"A print1"<<Std::endl; }};classD | Publica{ Public:    Virtual voidprint1 () {std::cout<<"B print1"<<Std::endl; }};classc{ Public:    Charch; Virtual voidPrint2 () {std::cout<<"C Print2"<<Std::endl; }};classB | PublicA Publicc{ Public:    intcd; Virtual voidprint1 () {std::cout<<"D print1"<<Std::endl; }    Virtual voidPrint2 () {std::cout<<"D Print2"<<Std::endl; }};intMain () {//Q1b b;//Output A print1//Q2Std::cout <<sizeof(D) <<std::endl;// -    return 0;}/*A1: The reason for output a print1 is that in the constructor of Class A, the constructor of object B has not been executed internally, so object B has not been initialized and there is no virtual function table, in the construction method of a The this pointer is a type,
So is the memory layout of the PRINT1//A2A that calls A is----------__vfptr = 0x00c0ae48 Const A:: ' vftable ' {for ' a '}----------C memory layout----------__vfptr = 0x00c0abd8 Const C:: ' vftable ' {for ' c '}ch = 0XCCCCCCCC----------D memory layout---------A = {__vfptr = 0x00c0ae48 const D:: ' Vftabl E ' {for ' A '}}b = {__vfptr = 0x00c0abd8 const D:: ' vftable ' {for ' C '} ch = 0xcccccccc}CD = 0XCCCCCCCC---------

So sizeof (D) = 4 + 8 + 4 (the size of C is 8 because memory has to be on it)*/

C + + class inheritance-small note

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.