What is virtual function?
A virtual function is a member function in the base class that we expect to redefine in derived classes.
Basically a virtual function is used in the base class in order to ensure that the function is overriden.
This especially applies to cases where a pointer of base class points to an object of a derived class.
Here is a basic example which demonstrates how virtual function works.
#include <iostream>
#include <string>
class Entity
{
public:
virtual std::string GetName() { return "Entity"; }
};
class Person: public Entity
{
private:
std::string m_Name;
public:
Person(const std::string& name) : m_Name(name) {}
std::string GetName() { return m_Name; }
};
void print(Entity* entity)
{
std::cout << entity->GetName() << std::endl;
}
int main()
{
Entity* e = new Entity();
print(e);
Person* p = new Person("Jacky");
print(p);
delete e;
delete p;
return 0;
}
// OutPut:
// Entity
// Jacky