Short Answer
Short Answer
A virtual function is that function in the class which can be declared in the base class and if we have to redefine it again so we make use of the drive class and again redefine it .So by making a function virtual we can make it value being changed. Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class.
Example:
Class A { int a; public: A() { a = 1; } virtual void show() { cout <<a; } }; Class B: public A { int b; public: B() { b = 2; } virtual void show() { cout <<b; } };
The main of the code will be as following int main() { A *pA; B oB; pA = &oB; pA->show(); return 0; }
Output :
2
Q2- What is a virtual base class? Explain with an example. Why we need them?
A virtual base class is one class abc { virtual void print() =0 } you cannot instantiate a virtual base class for you to create an object you will have to over ride pure virtual methods in your inherited class.
Example:
Virtual Class A { Void show{} } Class B:public class A{ Void show() } Class C:public class A{ Void show() } Class D : public class c, public class b{}
Example:
Virtual void show=0 { }