C++ Interview

Virtual Function in C++

A virtual function is a member function of the parent class that is defined by using the "virtual " keyword. These functions derived by the child class and call by the pointer or object of the parent class. And execute the derived class of the function.

A virtual function is a member function of the parent class that is defined by using the “virtual ” keyword. These functions derived by the child class and call by the pointer or object of the parent class. And execute the derived class of the function.

Why use Virtual Function?

Int type pointer can store the address of int type, float type pointer can store the address of float type but pointer type of parent class can also store the address of their child class object.

For example :

#include <iostream>

using namespace std;

class app
{
    public:
    int call()
    {
        cout<<"No Internet call available";
    }
};

class newApp : public app
{
    public:
    int call()
    {
        cout<<"Internet call available";
    }
};

int main()
{
   // create poniter type of parent class p and parent class object obj1
    app *p,obj1;
   // create object of child class
    newApp obj2;
    // here pointer p store the address of the object class of child class.
    p = &obj2;
    p->call();
    return 0;
}
No Internet call available

In the above example, we call function of child class because we store in p address of the base class. But function call of a parent class.

  • To resolve this problem Virtual function use.
  • Virtual keyword used before the function.
  • Virtual Function can actually say to compiler they do the late binding instead of early binding.
  • Due to late binding(during runtime) compiler gives the variable p to the address of the child class object.
  • In the early binding variable p not get the address. Therefore they call the function of pointer type.
  • In the below example, we use the virtual function.
#include <iostream>

using namespace std;

class app
{
    public:
    virtual int call()
    {
        cout<<"No Internet call available";
    }
};

class newApp : public app
{
    public:
    int call()
    {
        cout<<"Internet call available";
    }
};

int main()
{
    app *p,obj1;
    newApp obj2;
    p = &obj2;
    p->call();
    return 0;
}
Internet call available

 

Leave a Reply

%d bloggers like this: