C + +: virtual function of class and space occupied by virtual inheritance

Source: Internet
Author: User

Char takes up one byte, but does not satisfy a multiple of 4, the data is aligned, using bytes (byte) in multiples of 4.

Gcc:

In GCC, either a virtual function or a virtual inheritance requires that the pointer be stored in a virtual function table, which occupies 4 bytes.

Inheritance inherits the base class's data, and the virtual function table, which is the space that inherits the base class.

Code:

* * * test.cpp * *  Created on:2014.04.20 * 
 author:spike/
      
/*eclipse CDT, gcc 4.8.1* /
      
#include <iostream>  
      
using namespace std;  
      
Class A {  
    char k[5];  
Public:  
    virtual void aa () {};  
      
Class B:virtual public A {  
    char j[6];  
Public:  
    virtual void bb () {};  
};  
      
Class C:virtual public B {  
    char i[7];  
Public:  
    virtual void cc () {};  
      
int main () {  
    std::cout << "sizeof (a) =" << sizeof (a) << Std::endl;  
    Std::cout << "sizeof (b) =" << sizeof (b) << Std::endl;  
    Std::cout << "sizeof (c) =" << sizeof (c) << Std::endl;  
      
    return 0;  
}

Output:

sizeof (A) =  
sizeof (B) =  
sizeof (C) = 36

Vs:

VS, in normal circumstances, all virtual functions are written in a virtual function table, that is, the derived class uses a virtual function table of the base class, and does not create a virtual function table of bytes;

If you use virtual inheritance, the derived class creates a new virtual function table and a virtual inheritance table, that is, an additional 8 bytes (two tables);

Output:

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

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.