Sobes.tech
Junior

What do you know about the 'virtual' keyword in C++?

sobes.tech AI

Answer from AI

virtual in C++ is used to declare virtual functions in a base class. This allows for runtime polymorphism.

Application:

  • Defines a function in the base class that can be overridden in derived classes.
  • When calling a virtual function through a pointer or reference to the base class, the actual implementation in the derived class object is called (if overridden). This is done at runtime via the virtual function table (vtable).

Main points:

  • Only member functions of a class can be virtual. Global functions, static member functions, and constructors cannot be virtual.
  • Destructors can and often should be virtual to avoid memory leaks when deleting derived class objects through a base class pointer.
  • If a function is declared virtual in the base class, it remains virtual in all derived classes, even if virtual is not explicitly used there (though explicitly using virtual and override in derived classes is recommended for clarity).
  • Pure virtual functions are declared with = 0 and make the class abstract. Such a class cannot be instantiated directly.

Example:

#include <iostream>

class Base {
public:
    virtual void print() {
        std::cout << "From Base" << std::endl;
    }

    virtual ~Base() {
        std::cout << "Base destructor" << std::endl;
    }
};

class Derived : public Base {
public:
    void print() override { // Using override for explicit override
        std::cout << "From Derived" << std::endl;
    }

    ~Derived() override { // Using override
        std::cout << "Derived destructor" << std::endl;
    }
};

int main() {
    Base* ptr = new Derived(); // Base class pointer points to a derived object

    ptr->print(); // Calls Derived::print() due to virtual function
    delete ptr;   // Calls Derived destructor, then Base destructor due to virtual destructor

    return 0;
}

Related concepts:

  • vtable (virtual function table): A table of pointers to virtual functions of a class. Each object with virtual functions contains an invisible pointer (vptr) to its class's vtable.
  • vptr (pointer to vtable): Needed to determine the called function at runtime.
  • = 0 (pure virtual function): Indicates that the function has no implementation in this class, making it abstract.
  • override (override specifier): Explicitly indicates that a function in a derived class overrides a virtual function of the base class. Helps the compiler catch errors if the function signature does not match.
  • final (specifier): Prevents further overriding of a virtual function or inheritance from a class.

In short: virtual is the main mechanism for implementing polymorphism through inheritance and dynamic function binding in C++.