C++ Vertual Function Interview Questions and Answers
What is a virtual base class?
An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class.
C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.
What is Virtual Table?
A virtual table is a mechanism to perform dynamic polymorphism i.e., run time binging. Virtual table is used to resolve the function calls at runtime. Every class that uses virtual functions is provided with its own virtual functions.
Every entry in the virtual table is a pointer that points to the derived function that is accessible by that class. A hidden pointer is added by a compiler to the base class which in turn calls *_vptr which is automatically set when an instance of the class is created and it points to the virtual table for that class..
Overloading vs. overriding
Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance.
Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be same.
Overridden functions are in different scopes; whereas overloaded functions are in same scope.
Overriding is needed when derived class function has to do some added or different job than the base class function.
Overloading is used to have same name functions which behave differently depending upon parameters passed to them.
What is the use of Vtable?
Vtables are used for virtual functions. Its a shortform for Virtual Function Table.
It's a static table created by the compiler. Compiler creates a static table per class and the data consists on pointers to the virtual function definitions. They are automatically initialised by the compiler's constructor code.
What are pure virtual functions?
Pure virtual functions are also called ‘do nothing functions’.
e.g. virtual void abc() = 0;
When a pure virtual fnction is declared in the base class, the compiler necessitates the derived classes to define those functions or redeclare them are pure virtual functions. The classes containing pure virtual functions cannot be used to declare objects of their own. Such classes are called as abstract base classes.