If a function present in Base class is overridden in derived class then Inheritance has ambiguity .So virtual keyword is used to overcome this and at run time which function to call can be decided by using Base class pointer to point to either Base class object or Derived class object like below:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void display()
{
cout<<"Inside Base\n";
}
};
class Derived:public Base
{
public:
void display()
{
cout<<"Inside derived\n";
}
};
int main()
{
Derived d;
Base b;
Base *bp;
bp=&b;
bp->display();
bp=&d;
bp->display();
}
Same can be achieved by using scope resolution operator which function to call is solved like the example givenn beow:
#include <iostream>
using namespace std;
class Base
{
public:
void display()
{
cout<<"Inside Base\n";
}
};
class Derived:public Base
{
public:
void display()
{
cout<<"Inside derived\n";
}
};
int main()
{
Derived d;
d.Base::display();//invokes display() in Base
d.Derived::display();//invokes display in Derived
return 0;
}
So my question is why virtual functions are needed if same task can be achieved by scope resolution operator?