C++ Virtual Functions Question:
Download Questions PDF

What is virtual function?

Answer:

A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.

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, this is how virtual functions support runtime polymorphism.

Consider following program code:

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;
}
};

int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}

Output is 2 since pA points to object of B and show() is virtual in base class A.

Download C++ Virtual Functions Interview Questions And Answers PDF

Previous QuestionNext Question
What is Object slicing?What is Virtual Table?