liveBook · Manning

Virtual keyword

As explained in 100 C++ Mistakes and How to Avoid Them

The C++ virtual specifier declares a member function as participating in virtual dispatch and signals that a class is intended to support inheritance-based polymorphism.

The virtual keyword marks a member function for inheritance-based polymorphism. A derived function can replace base behavior, but a typo such as aria() creates a new method while compilation still succeeds. section 2.3

A compiling mistake

Shape defines virtual double area() const, but Square defines double aria() const. Calls through Shape* therefore use the base implementation instead of calculating the square's area. Writing double area() const override makes the compiler reject the mismatch.

A polymorphic base also needs a virtual destructor. Deleting a derived object through a base pointer otherwise destroys only the base portion, potentially leaking derived resources. section 8.8

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains dispatch, override checking, and destructor order through code examples, but does not detail implementation internals.
Examples
Uses Shape, Square, and Circle examples plus destructor output showing missing versus complete cleanup.
What it assumes
Assumes basic classes, inheritance, pointers, and member functions while teaching the relevant polymorphism hazards through examples.
What you can do after
Diagnose misnamed overrides and incomplete destruction, then apply override and virtual destructors to polymorphic classes.
How it connects
Connects virtual functions with inheritance, polymorphism, override, virtual destructors, and base-pointer deletion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.