Wednesday, October 17, 2007

Virtual function

Well, Today we will talk about a trick in virtual functions
Suppose we have two classes
class A
{
private:
int x;
public:
A()
{
x = 0;
}
void printX()
{
//print x value
}
}

class B
{
private:
int x;
public:
B()
{
x = 0;
}
virtual void printX()
{
//print X value
}

}

Question now: What are size of classes A and B?!

Size of class A = 4 bytes while size of class B = 8 bytes, but Why?!

Classes that contain virtual functions, has a pointer to table that referes to virtual function addresses;
so simply class B contains
int x ==> 4 bytes
pointer to virtual functions table ==> 4 bytes
total ==> 8 bytes

1 comment:

GameCanvas said...

nice info...
thanks