#include<iostream>
using namespace std;
class A
{
};
class B
{
public:
void disp()
{
cout<<" This is not virtual function.";
}
};
class C
{
public:
virtual void disp()
{
cout<<"This is virtual function.";
}
};
int main()
{
cout<<"class A"<<sizeof(A)<<endl;
cout<<"class B"<<sizeof(B)<<endl;
cout<<"class C"<<sizeof(C)<<endl;
return 0;
}
sizeof class A and class B are both 1 byte only.What about the memory allocation for member function disp in B.
For each instance of the class, memory is allocated to only its member variables i.e. each instance of the class doesn’t get it’s own copy of the member function. All instances share the same member function code. You can imagine it as compiler passing a hidden this pointer for each member function so that it operates on the correct object. In your case, since C++ standard explictly prohibits 0 sized objects, class A and class B have the minimum possible size of 1. In case of class C since there is a virtual function each instance of the class C will have a pointer to its v-table (this is compiler specific though). So the sizeof this class will be sizeof(pointer).