#include<iostream>
using namespace std;
class X
{
int a;
int b;
public:
void f(int a)
{
cout<<"\nInside X";
}
virtual void abc ()
{
cout<<"\nHello X";
}
};
class Y : public X
{
int a;
public:
void f(int a, int b)
{
cout<<"\nInside Y";
}
void abc()
{
cout<<"\nHello Y";
}
};
int main()
{
X a;
cout<<sizeof(X);
Y b;
cout<<sizeof(Y);
X *h = new Y;
h->abc();
}
I understand that the reason the size of class X is 12 bytes, is because it contains a vptr (virtual pointer) to the virtual table. Is there anyway I could read this virtual table and if not, could at least access the virtual pointer. I tried using unions, but it gave me some kind of error.
Also, when I call h->abc() , how does it know the object of class, h is pointing to? I thought most of this was done at compile time. But when you have a base class pointer pointing to a derived class, how does it know which class function to execute.
Consider these two situations
X *h = new X;
h->abc();/* This would call the abc function in X */
and
X *h = new Y;
h->abc();/* This would call the abc function in Y*/
I read, that the h pointer would go to the vtable of the object it is pointing to and would hence call that function? But how is this achieved in runtime?
