In this article, we will discuss the size of C++ classes. We will look into an empty class, a class with member function, a class with virtual functions, and a class with data members.
We will be using a 64-bit machine to compile the test code. For a 64-bit machine, the pointer size is 8 bytes.
Size of empty class
The size of an empty c++ class is 1 byte. It is to ensure that the addresses of two different objects will be different.
#include <iostream>
using namespace std;
class empty{
};
int main()
{
cout<< "Size of empty class : "<<sizeof(empty)<<endl;
return 0;
}
Output
Size of empty class : 1
Class with a member function
Let’s consider a class with one member function.
#include <iostream>
using namespace std;
class Shape{
public:
void draw(){cout <<"shape";}
};
int main()
{
cout<< "Size of shape class : "<<sizeof(Shape)<<endl;
return 0;
}
Output
Size of shape class : 1
So adding member functions doesn’t change the class size. What about virtual functions?
Class with virtual function
Let’s consider a class with a virtual function. Do you think its size is still 1 byte?
#include <iostream>
using namespace std;
class Shape{
public:
virtual void draw(){cout <<"shape";}
};
int main()
{
cout<< "Size of shape class with virtual function : "<<sizeof(Shape)<<endl;
return 0;
}
Output
Size of shape class with virtual function : 8
For classes with virtual functions, the compiler will add a hidden pointer known as a virtual pointer(VPTR). The size of a pointer is in a 32-bit platform is 4 bytes. Here we are using the 64-bit machine so it is 8 bytes.
Class with data members
Let’s consider a class with member variables.
#include <iostream>
using namespace std;
class Shape{
public:
int a;
};
int main()
{
cout<< "Size of shape class with data member : "<<sizeof(Shape)<<endl;
return 0;
}
Output
Size of shape class with data member: 4
Here the size of the class changed based on the data type of the member variable. The int data type will take 4 bytes of memory.
Conclusion
In conclusion, we can summarize the size of C++ classes as
- The Size of empty class : 1 byte
- Size of class with member function(s) : 1 byte
- Size of class with virtual functions : 8 bytes on 64-bit platform or 4 bytes on 32-bit platform