• Virtual function is a member function which is re-defined by a derived class and declared within a base class.
  • When you refer to a derived class object using a reference or pointer to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
  • It ensures that the correct function is called for an object, regardless of the type of reference used for function call.
  • It is mainly used to achieve Run-time polymorphism.
  • In base class functions are declared with a virtual. At run time the resolving of function call is done.

Sample Code

using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class\n";
}

void show()
{
cout << "show base class\n";
}
};

class derived : public base {
public:
void print()
{
cout << "print derived class\n";
}

void show()
{
cout << "show derived class\n";
}
};

int main()
{
base *bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime
bptr->print();

// Non-virtual function, binded at compile time
bptr->show();

return 0;
}

Output

Categorized in: