Size of C++ classes

前端 未结 3 1435
予麋鹿
予麋鹿 2021-02-07 12:06

Here is the code which prints size of different classes

#include 

using namespace std;

class EmptyClass
{    
};

class AbstractClass
{
  publi         


        
相关标签:
3条回答
  • 2021-02-07 12:40

    NotAbstrClass is like an empty class when we talk about bit sizes since it has no data. MixClass has the virtual function pointer (4 bytes on a 32-bit machine) and an int (also 4 bytes).

    0 讨论(0)
  • 2021-02-07 12:42

    NotAbstrClass has no data members, so it too is an empty class. Since classes cannot be zero-sized, you get the same treatment as EmptyClass.

    MixClass has a virtual function, and 1 non-static data member. It seems each of these (vptr and int) occupy 4 bytes on your platform, so the size is 8 bytes.

    0 讨论(0)
  • 2021-02-07 12:53

    According to Girish Shetty:

    There are many factors that decide the size of an object of a class in C++.

    These factors are:

    • Size of all non-static data members
    • Order of data members
    • Byte alignment or byte padding
    • Size of its immediate base class
    • The existence of virtual function(s) (Dynamic polymorphism using virtual functions).
    • Compiler being used
    • Mode of inheritance (virtual inheritance)

    Here there are some related website, I think it can be helpful to you.

    Determine the size of class object: http://www.cprogramming.com/tutorial/size_of_class_object.html

    Memory layout: http://www.phpcompiler.org/articles/virtualinheritance.html

    And, if you use MVSC, you can dump all memory layout of all class in your solution with -d1reportAllClassLayout like that:

    cl -d1reportAllClassLayout main.cpp
    
    0 讨论(0)
提交回复
热议问题