Table of contents
WHAT IS VTable?
It stands for "VIRTUAL TABLE". It is created by the compiler to support dynamic polymorphism. When class contain virtual function, compiler creates VTable for that class.
WHAT IS Vptr?
It stands for "VIRTUAL POINTER". It is a hidden pointer that is added by the compiler as a member of class to point to the VTable of that class.
IMPLEMENTATION:
class A{
public:
virtual void fun1(){
cout<<"base function 1";
}
virtual void fun2(){
cout<<"base function 2";
}
virtual void fun3(){
cout<<"base function 3";
}
};
class B:public A{
public:
void fun1(){
cout<<"derived class1 fun1 override";
}
};
class C:public B{
public:
void fun2(){
cout<<"derived class2 fun2";
}
};
int main(){
A* ptr1=new A();
A* ptr2=new B();
A* ptr3=new C();
ptr1->fun1();
ptr1->fun1();
ptr1->fun2();
ptr1->fun3();
ptr2->fun1();
ptr2->fun2();
ptr2->fun3();
ptr3->fun2();
ptr3->fun3();
delete ptr1;
delete ptr2;
delete ptr3;
return 0;
}
DIAGRAM REPRESENTATION OF VTABLE:
TYPECASTING
It is basically of two types:-
UPCASTING
Definition: Means conversion from derived class to base class.
SYNTAX:
base* pointer_variable;
derived_class obj_name;
pointer_variable of base= & object_name of derived class;
EXAMPLE:
A *ptr;
B obj;
ptr=& obj;
DOWNCASTING
Definition: Means conversion from base class to derived class. It is also called manually or forcefully typecasting.
SYNTAX:
derived_class *pointer_variable;
base_class obj_name;
pointer_variable of derived class=(derived_class*) & object_of_base;
EXAMPLE:
A obj;
B *ptr;
ptr=(B*) & obj;