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


