Here is the code which prints size of different classes
#include <iostream>
using namespace std;
class EmptyClass
{
};
class AbstractClass
{
public:
virtual void funcOne() = 0;
virtual void funcTwo() = 0;
};
class NotAbstrClass
{
public: int virtFunc( int );
};
class MixClass
{
public:
virtual void clFunc( int );
static int i;
int j;
};
int main()
{
// Print size of class or class objects
cout<<"Size of empty class: "<< sizeof(EmptyClass)<<endl;
cout<<"Size of Abstract class :"<< sizeof(AbstractClass)<<endl;
cout<<"Size of Non Abstract class: "<< sizeof(NotAbstrClass)<<endl;
cout<<"Size of Mix class: "<< sizeof(MixClass)<<endl;
return 0;
}
The output of the program on C++11 compiler is
Size of empty class: 1
Size of Abstract class :4
Size of Non Abstract class: 1
Size of Mix class: 8
I understand why Empty class has size 1 Size of empty class object. For abstract class, the object stores a pointer for implementing virtual function call mechanisms. But what about the sizes of other class objects (NotAbstrClass and MixClass) ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With