This question is one of the big doubts that looms around my head and is also hard to describe it in terms of words . Some times it seems obvious and sometimes a tough one to crack.So the question goes like this::
class Base{ public: int a_number; Base(){} virtual void function1() {} virtual void function2() {} void function3() {} }; class Derived:public Base{ public: Derived():Base() {} void function1() {cout << "Derived from Base" << endl; virtual void function4() {cout << "Only in derived" << endl;} }; int main(){ Derived *der_ptr = new Derived(); Base *b_ptr = der_ptr; // As just address is being passed , b_ptr points to derived object b_ptr -> function4(); // Will Give Compilation ERROR!! b_ptr -> function1(); // Calls the Derived class overridden method return 0; }
Q1. Though b_ptr is pointing to Derived object, to which VTABLE it accesses and HOW ? as b_ptr -> function4() gives compilation error. Or is it that b_ptr can access only upto that size of Base class VTABLE in Derived VTABLE?
Q2. Since the memory layout of the Derived must be (Base,Derived) , is the VTABLE of the Base class also included in the memory layout of the Derived class?
Q3. Since the function1 and function2 of base class Vtable points to the Base class implementation and function2 of Derived class points to function2 of Base class, Is there really a need of VTABLE in the Base class?? (This might be the dumbest question I can ever ask, but still I am in doubt about this in my present state and the answer must be related to answer of Q1 :) )
Please Comment.
Thanks for the patience.