Size of the C ++ sizeof computing class

Source: Internet
Author: User

The computing class only considers the size of member variables, not the size of member functions!

However, if the class contains a virtual function, an additional 4 bytes will be added in the computing class size! These four bytes are the number of bytes occupied by the virtual function table!

Note the memory alignment when computing classes are large!

Let's look at an example:

Class ctest
{
Char ch;
}; // Sizeof (ctest) = 1 class ctest
{
Char ch;
Int num;
};

// Sizeof (ctest) = 8

It's strange why the second ctest is 8 bytes in size, and memory alignment is involved here

The Int size is 4 bytes, so the CH is filled with 3 bytes due to memory! Therefore, the ctest size is 8 bytes.

 

Let's take a look at the following column:

Class ctest
{
Char ch;
Int num;
Double B;
};

// Sizeof (ctest) = 16

Here CH + num = 5 bytes, fill in the size of B, that is, 8 bytes!

Class ctest
{
Char ch;

Double B;
Int num;
};

// Sizeof (ctest) = 24

Both CH and num are filled in 8 bytes.

 

Inherit class size

Class CT1 ()
{
Int num;
};

Class CT2: Public CT1
{
Int val;
};

// Sizeof (CT2) = 4 + 4 = 8;

Sizeof (inherited class) = size of its member variable + parent class. If it is a virtualized child, add another size pointing to the parent class pointer.

If the C1 and C2 classes inherit the Class C3 containing virtual functions, and the class C4 inherits both C1 and C2, then C4 retains only one pointer pointing to the Class C3 of the virtual base class.

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.