H
harry
Hi ppl
I have a question about memory layout of a class. Consider the code
below:
class Base1 {
virtual void f() { cout << "Base1::f" << endl; }
virtual void g() { cout << "Base1::g" << endl; }
};
class Drive : public Base1{
public:
virtual void fd() { cout << "Drive::fd" << endl; }
virtual void gd() { cout << "Drive::gd" << endl; }
};
typedef void(*Fun)(void);
int main() {
Drive objDrive;
Fun pFun = NULL;
int *temp1=(int*)&objDrive+0;
int *temp2=(int*)(*temp1);
pFun=(Fun)((int*)*(temp2+0));
pFun();
temp1=(int*)&objDrive+0;
temp2=(int*)(*temp1);
int *temp3 = (int*)*(temp2+1);
pFun=(Fun)temp3;
pFun();
return 0;
}
This outputs:
Base1::f
Base1::g
This is understandable because of the VPTR and VTable being created
when the derived class object is made. Note that though the virtual
function was private to base class, it can still be called from the
derived class object. Now my question is:
What happens if the base class functions were not virtual but normal
functions? Is there any way we can access the function pointers of
these private member functions from the derived class object?? What is
the memory layout of the derived class object that would be created in
this case?
Thanks in advance
Harry
I have a question about memory layout of a class. Consider the code
below:
class Base1 {
virtual void f() { cout << "Base1::f" << endl; }
virtual void g() { cout << "Base1::g" << endl; }
};
class Drive : public Base1{
public:
virtual void fd() { cout << "Drive::fd" << endl; }
virtual void gd() { cout << "Drive::gd" << endl; }
};
typedef void(*Fun)(void);
int main() {
Drive objDrive;
Fun pFun = NULL;
int *temp1=(int*)&objDrive+0;
int *temp2=(int*)(*temp1);
pFun=(Fun)((int*)*(temp2+0));
pFun();
temp1=(int*)&objDrive+0;
temp2=(int*)(*temp1);
int *temp3 = (int*)*(temp2+1);
pFun=(Fun)temp3;
pFun();
return 0;
}
This outputs:
Base1::f
Base1::g
This is understandable because of the VPTR and VTable being created
when the derived class object is made. Note that though the virtual
function was private to base class, it can still be called from the
derived class object. Now my question is:
What happens if the base class functions were not virtual but normal
functions? Is there any way we can access the function pointers of
these private member functions from the derived class object?? What is
the memory layout of the derived class object that would be created in
this case?
Thanks in advance
Harry