Surely the compiler is smart enough to deduce exactly what function you want for some cases, yet how come other cases require run-time support?
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overriden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. Functions are declared with a virtual keyword in base class. The resolving of function call is done at runtime.
Virtual functions are slow when you have a cache miss looking them up. As we'll see through benchmarks, they can be very slow. They can also be very fast when used carefully — to the point where it's impossible to measure the overhead.
The main use of virtual function is to achieve Runtime Polymorphism. Runtime polymorphism can be achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class.
Because we don't always know, what instance we will face at runtime.
For example, you have classes: SuperClass
, Subclass1
and Subclass2
, and they all have a method doACoolThing()
. The user presses a button 0
, 1
or 2
, and, depending on his input, an instance of the appropriate class is created, and its doACoolThing()
method is called.
There is no way for us (and the compiler too) to figure out what class's method will be called at runtime.
That's why such tricks require a runtime support.
A small example to illustrate an idea (P.S. don't write the code like this, it's here just to illustrate polymorphism :) ):
#include <iostream>
using namespace std;
class SuperClass
{
public:
virtual void doACoolThing();
};
void SuperClass::doACoolThing()
{
cout << "Hello from the SuperClass!" << endl;
}
class Subclass1 : public SuperClass
{
virtual void doACoolThing() override;
};
void Subclass1::doACoolThing()
{
cout << "Hello from the Subclass1" << endl;
}
class Subclass2 : public SuperClass
{
virtual void doACoolThing() override;
};
void Subclass2::doACoolThing()
{
cout << "Hello from the Subclass2" << endl;
}
int main()
{
int userInput;
cout << "Enter 0, 1 or 2: ";
cin >> userInput;
SuperClass *instance = nullptr;
switch (userInput)
{
case 0:
instance = new SuperClass();
break;
case 1:
instance = new Subclass1();
break;
case 2:
instance = new Subclass2();
break;
default:
cout << "Unknown input!";
}
if (instance)
{
instance->doACoolThing();
delete instance;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With