I have been reading up on vptr and vptr_tables, and so far, I think I got the grasp of the basic concept.
#include <iostream>
class BaseA
{
public:
void fun() { std::cout<<"BaseA Fun\n"; }
};
class DerivedA : public BaseA
{
public:
void fun() { std::cout<<"DerivedA Fun\n"; }
};
class BaseB
{
public:
virtual void fun() { std::cout<<"BaseB Fun\n"; }
};
class DerivedB : public BaseB
{
public:
void fun() { std::cout<<"DerivedB Fun\n"; }
};
class BaseC
{
public:
virtual void fun1() { std::cout<<"BaseC Fun1\n"; }
virtual void fun2() { std::cout<<"BaseC Fun2\n"; }
};
class DerivedC : public BaseC
{
public:
void fun1() { std::cout<<"DerivedC Fun1\n"; }
void fun2() { std::cout<<"DerivedC Fun2\n"; }
};
class BaseD
{
public:
virtual void fun1() = 0;
virtual void fun2() = 0;
};
class DerivedD : public BaseD
{
public:
void fun1() { std::cout<<"DerivedD Fun1\n"; }
void fun2() { std::cout<<"DerivedD Fun2\n"; }
};
int main()
{
BaseA b_a;
DerivedA d_a;
std::cout<< sizeof(b_a) << " " << sizeof(d_a) << std::endl;
BaseB b_b;
DerivedB d_b;
std::cout<< sizeof(b_b) << " " << sizeof(d_b) << std::endl;
BaseC b_c;
DerivedC d_c;
std::cout<< sizeof(b_c) << " " << sizeof(d_c) << std::endl;
return 0;
}
One thing that is confusing me : I was under the assumption that the vtable contains one entry for each virtual function in the class. So, as the number of entries/functions increase, the object size should also increase, right?
However in the code snippet, both the second and third cout print 8 8, which means there exists the same amount of data in both objects. Why does this happen? My best guess is that the object simply contains a pointer to the vtable, and not individual pointers to all the virtual functions. That lookup is done during the runtime on demand. Is this right, or is there something else going on under the hood? And, does this change from compiler to compiler?