C/Virtual pointer
Expert: Prince M. Premnath - 10/24/2006
Questionsir i wanna know about the concept of virtual pointer..?
It has been asked in interviews as well as a new concept for me...! i m working in C/C++ environment since last 6 years.so i have a good relation with C/C++.Please rectify my doubts...?
Answer
Dear Neeraj!
I'm not sure to what you are referring.( may be pointer to virtual functions) if so follow the answer !
In order to achieve run time polymorphism its necessary to use a single pointer that can refer object of different classes , Here we use the pointer to BASE Class to refer to all the derived objects !
How to do that ?
Use same function name in both base and derived classes
The function in the base class is declared as virtual using "virtual" key word
Upon doing this The C Compiler determine which function to be executed during runtime based on the object pointed by the base pointer rather than the type of pointer , by making pointing to different objects we can invoke different version of virtual functions.
Eg:
class B // Class Base
{
void d(){ cout<<"Display base D"; }
virtual void c(){ cout<<"Display base C"; }
};
class D : public B // Derived class
{
void d() { cout<<" Display derived D" ; }
void c() { cout<<" Display derived C" ; }
};
void main()
{
B obj1;
D obj2;
B* bptr ;
cout<<" Base pointer pointing to base :";
bptr = &B; // ASSIGN BASE ADDRESS
bptr-> d();// INVOKES BASE
bptr -> c(); // INVOKES BASE
bptr = &D;// ASSIGN DERIVED CLASS ADDRESS
bptr-> d();// INVOKE BASE
bptr -> c();// INVOKE DERIVED
}
Regards!
Prince M. Premnath