MCQ on virtual function, VPTR, VTABLE and destructors etc. for interview exams preparation. These multiple-choice questions on virtual concepts contain the answer and explanation.
Q) Which concept is not available in C++?
- Virtual constructor
- Virtual destructor
- Virtual function
- Virtual Table
Answer: 1
There is no concept of virtual constructor in C++ programming. Read why virtual constructor is not possible in C++.
Q) What is output of the following C++ program?
class A{
public:
void f(){
cout<<"A::f()"<<endl;
}
};
class B:public A{
public:
void fb(){
cout<<"A::fb()"<<endl;
}
};
class C:public A{
public:
void fc(){
cout<<"A::fc()"<<endl;
}
};
class D: public B,public C{
public:
void fd(){
cout<<"A::fd()"<<endl;
}
};
int main(){
D obj;
obj.f();
return 0;
}
- A::f()
- A::f() A::f()
- A::f() A::f()
- Compiler error
Answer: 4
Explanation: The above class represent the virtual base class / diamond problem in C++. The object D will try to access the function f() of base class via class B and class C. as both B and C inherites A. This will lead to ambiguity call the function.
So, compiler will flash an error. i.e. ambiguous access of f().
If we make the class B and C virtual like below, then there would not be any ambiguity and program will work fine.
class A { public: void f() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};
Q) What is purpose of Virtual destructor?
- To maintain the call hierarchy of destructors of base and derived classes.
- Destructor can be virtual so that we can override the destructor of base class in derived class.
- Virtual destructor is to destroy the VTable
- None
Answer: 1
Base class destructor is made virtual in inheritance relationship to maintain the call of destructors in base and derived class. Note that first derived class destructor will be called then derived class. Read execution of order of constructors and destructors in C++. Also, Read why and when virtual destructor is useful ?
Q) When VTABLE (Virtual table) get created for a class?
- Every class by default has virtual table
- When a Class Overrides the function of Base class
- When a class contains at least one virtual function.
- When a class is derived from a base class.
Answer: 3
Q) Number of VTable created for following C++ program is ________
class A {
public:
virtual void f(){
cout<<"function :f()"<<endl;
}
};
int main(){
A obj1, obj2,obj3;
return 0;
}
- 0
- 1
- 3
- 4
Answer: 2
Compiler will create only 1 virtual table for the class. Virtual table does not depend upon number of objects created.