Virtual Keyword - RJAE5/2143-OOP GitHub Wiki

Virtual Keyword

In C++, the virtual keyword is used primarily to support polymorphism in Object-Oriented Programming. It is applied to member functions in base classes to allow derived classes to override them, enabling dynamic function calls (i.e., the function to be called is determined at runtime based on the object's actual type, not its declared type). This is essential for achieving runtime polymorphism.

Virtual Methods

When a function is declared virtual in a base class, it can be overridden in any derived class. The function call is then resolved at runtime using the actual type of the object, not the pointer or reference type used to call the function.

Virtual Method Example

class A
{
public:
    // Virtual is like a "contract" saying this function probably will get overridden
    virtual void show() {std::cout << "Showing from A!" << std::endl;} 
};

class B : public A
{
public:
    // The `override` keyword is not strictly necessary, it just acknowledges that it is overriding the base class function
    void show() override {std::cout << "Showing from B!" << std::endl;}
};

int main()
{
    A a;
    B b;

    a.show(); // Would use the virtual `show()` function from class `A` since the object is of type `A`
    b.show(); // Would use the overridden `show()` function from class `B` since the object is of type `B`
}

The following output does exactly as you would expect, however the main idea of the virtual keyword is that during runtime, it decided which class to return to and use the appropriate show() function

Showing from A!
Showing from B!

Pure Virtual Functions

A pure virtual function is necessary for both abstract classes and interfaces. It is intended to be used in a base class and instead of defining a function body, you set the entire function equal to 0, this is called a "null function body":

virtual void myFunc() = 0;

This stops any class that contains a PV function from being instantiated directly and forces derived classes to override this function and give it a definition.

Important Notes

  • The virtual keyword is necessary for runtime polymorphism.
  • Declaring a virtual function is similar to a "contract" stating that the function likely will get overridden down the inheritance chain.
  • Pure virtual functions are the defining factor of abstract classes and interfaces, and force derived classes to implement those function bodies.

Sources:

  1. https://www.geeksforgeeks.org/virtual-function-cpp/
  2. https://learn.microsoft.com/en-us/cpp/cpp/virtual-functions?view=msvc-170