>

Thursday, 17 December 2015

size of classes

#include "stdafx.h"
#include
using namespace std;
class example1
{
private:
int a,b;
};
class example2:public example1
{
public:
virtual void f1(){}
};
class example3
{
public:
virtual void f2(){}
virtual void f3(){}
};
class dervied:public example2,example3
{
};
class derived1:public example2,example3
{
private:
int a;
public:
virtual void der(){}
};
void main()
{
//case 1:size of a class with 2 data members
example1 e1;
cout<<sizeof(e1)<<endl; // size = 8(2 * size of int)
//Case 2:Size of derived class with one virtual function
example2 e2;
cout<<sizeof(e2)<<endl; //size = 12 (size of VPTR(4 bytes) + 8)
//Case 3: Size of a class with 2 or more virtual functions
example3 e3;
cout<<sizeof(e3)<<endl; //size = 4 (size of VPTR)
//case 4: Size of a class which is derived from multiple classes
dervied der;
cout<<sizeof(der)<<endl; //size = 16 (sum of sizes of individual
// classes + size of data members in class)
//Case 5: Size of derived class with one virtual function
derived1 der1;
cout<<sizeof(der1)<<endl; //size - 20
}

0 comments:

Post a Comment