Dover Organization Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
Virtual Function is a very important aspect of inheritance in any object-oriented language.
Suppose you have a base class A and child class B.
{class A{
protected virtual void func();
}
class B : public A
{
void func()
{
some code;
}
}
A *a;
B b =new B();
a = &b;
a->func();
}
As you can see from this code, depending on the what object, the pointer 'a' points to, at run time it is decided that method func() in class B has to be called. This is called virtual function.
Now, when will it be useful?. Consider a big application source code which has a base class and several child classes inheriting from it. Just think about how much redundant code has to be written if we don't use virtual functions.
Virtual function: This is a technique for polymorphism in OOP. To understand it simply, suppose Class A is a Base class and Class B is Derived from A. and some func() is defined in both these classes i.e. function overriding. Now, we have a pointer to base class A and we want to ensure that right function is to be called based on the type of object this base class pointer is holding. so we simply declare func() in base as virtual func(). So whenever func() will be called with pointer holding derived class object, firstly func() of derived class will be called, but in case it is not defined in derived then ultimately base func() will get called.
- ptrip.jnu May 01, 2012is it helpful?
Pure virtual function: is often used for creating interfaces/abstract_classes. these functions may not have a body and it's mandatory to override it in derived classes..