C++ ยท Chapter 38 of 49

C++ Virtual Functions

A virtual function is declared with the `virtual` keyword in a base class and can be overridden in derived classes, enabling dynamic dispatch through base pointers/references. Marking a derived override with `override` helps the compiler catch mistakes.

A 'pure virtual function' (`virtual void draw() = 0;`) has no implementation and makes its class abstract โ€” it cannot be instantiated directly, only through derived classes.

Declaring and overriding

The base class marks a method `virtual`; derived classes redefine it with the same signature, optionally adding `override` for compiler-checked safety.

Pure virtual functions and abstract classes

`virtual void speak() = 0;` makes the class abstract. Any class with at least one pure virtual function cannot be instantiated, forcing subclasses to implement it.

Example 1 (cpp)
class Animal {
public:
    virtual void speak() = 0;
};
class Cat : public Animal {
public:
    void speak() override { std::cout << "Meow"; }
};
int main() {
    Animal* a = new Cat();
    a->speak();
    delete a;
}
Output
Meow

Animal is abstract due to the pure virtual speak(); Cat provides the implementation.

Key points

  • virtual enables a method to be overridden with dynamic dispatch.
  • override documents intent and catches signature mismatches.
  • = 0 makes a function pure virtual, and the class abstract.
  • Abstract classes cannot be instantiated directly.
๐Ÿ’ก Note: Always give a base class with virtual functions a virtual destructor to avoid resource leaks when deleting through a base pointer.

๐Ÿ“ Quick Quiz

1. What keyword marks a function as overridable?

2. What does '= 0' after a virtual function mean?

3. Can an abstract class be instantiated directly?