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.
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;
}MeowAnimal 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.
