liveBook · Manning

Virtual method

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

A virtual function is a C++ member function whose implementation can be dynamically selected through an object of a derived class.

A virtual method lets a derived class customize or replace inherited behavior when code uses a base-class pointer or reference. This mechanism enables polymorphism, but small mistakes can silently break the intended behavior. section 2.3 section 8.0

Mistake: defining a new method instead of overriding

A derived method must match the inherited virtual method exactly. In the example, Shape declares area(), but Square defines aria(). The code compiles because aria() is a new method; calls through Shape* therefore use Shape::area() instead of the intended square implementation. Writing double area() const override makes the compiler reject this typo and documents the intended relationship. section 2.3

Use virtual methods carefully in inheritance hierarchies:

  • Declare a method virtual in a class intended to serve as a polymorphic base. section 2.3
  • Mark derived implementations with override so signature or naming mistakes become compiler errors. section 2.3
  • Give a polymorphic base class a virtual destructor before deleting derived objects through a base pointer. section 8.8

Mistake: omitting the virtual destructor

Shape declares virtual area() but has a nonvirtual destructor. When main deletes a Square through Shape*, only ~Shape runs; ~Square does not release its dynamically allocated side, producing a leak and undefined behavior. Changing the declaration to virtual ~Shape() causes destruction to proceed through Square and then Shape. section 8.8

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

How deep it goes
Explains dispatch through pointers or references, override checking, and destructor consequences, but does not detail dispatch internals.
Examples
Demonstrates Shape, Square, and Circle examples containing a misspelled override and a missing virtual destructor.
What it assumes
Assumes basic C++ classes and inheritance while teaching virtual dispatch risks through concrete examples.
What you can do after
Apply polymorphism with compiler-checked overrides and destruct safely through base-class pointers.
How it connects
Connects virtual methods with inheritance, polymorphism, constructors, destructors, and class invariants.

Also explained in

Compare how 3 books explain virtual method →

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.