Q) What is VPTR ( V Table pointer)?
- Holds the address of the V table
- Holds the address of the virtual functions
- Holds the address of pure virtual functions
- None
Answer: 1
VPTR is used to hold the address of the VTable. This pointer is set internally into base class as public V table pointer and accessible to all derived classes
Q) Who initializes the VPTR?
- Constructor initialize the VPTR
- By default, initiation is done
- Class itself
- None
Answer – 1
Constructor initializes the VPTR.
Q) How many VTable will be created for following program?
//class A
class A {
public:
virtual void f(){
cout<<"A:f()"<<endl;
}
};
class D:public A{
void f(){
cout<<"B:f()"<<endl;
}
};
- 0
- 1
- 2
- 3
Answer: 3
Q) How many VPTR (Vtable pointer) will be created internally for following program?
class A {
public:
virtual void f(){
cout<<"A:f()"<<endl;
}
};
class D:public A{
void f(){
cout<<"B:f()"<<endl;
}
};
- 0
- 1
- 2
- 3
Answer: 2
For the above scenario, 2 virtual table will be created that is 1 for base class and another for derived class. But, compiler set only one public VPTR in base class internally. If 2nd Vtable is required to be initialized then the same VPTR is inherited and used at run time. Note that Constructors initializes the VPTR.
So, answer is 1 public VPTR in base class.
Q) In C++, virtual function is used in which concept?
- function overloading
- function overriding
- constructor overloading
- All of the above
Answer: 2
Virtual functions are used in function overriding concept in inheritance relationship