liveBook · Manning

Polymorphism

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

Polymorphism is the ability to use a common interface while selecting behavior according to an object's actual type.

Polymorphism lets code use a common interface while behavior depends on an object’s actual type. In C++, a base-class pointer or reference can refer to a derived object, and a call to a virtual function can use the derived implementation. section 8.7 section 8.8

A hierarchy needs a meaningful is-a relationship, not just an opportunity to reuse code. A Student is a Person, but making Horse inherit from Square gives a horse an inappropriate area method. Code using a collection of squares then needs special cases for horses. section 7.7

Listing 7.13 Using an interface-like class
class Moveable {                                             #1
public:
    virtual void move(int) = 0;
    virtual double getPosition() = 0;
};
 
class Square : public Moveable {
private:
    double side;
    double offset;
public:
    Square(double side) : side(side), offset(0) {}
    void move(int n) { this->offset += n*side; }             #2
    double getPosition() { return offset; }
    double area() { return side*side; }
};
 
class Horse : public Moveable {
private:
    double height;
    double position;
public:
    Horse(double height) : height(height), position(0) {}
    void move(int offset) { position += offset; }            #3
    double getPosition() { return position; }
};
 
int main() {
    std::vector<Moveable*> movers;                           #4
    movers.push_back(new Square(1));
    movers.push_back(new Horse(15));
    for (int i = 0; i < movers.size(); ++i) {
        movers[i]->move(2);
        std::cout << "Mover moved " << movers[i]->getPosition() << " units \n";
    }
    return 0;
}

A shared Moveable interface lets Square and Horse provide their own movement behavior without claiming that a horse is a square. section 7.7

Preserve the derived object when using it through the base type. Storing a Student by value in an array of Person objects slices off the Student part, including its GPA. A base-class reference can instead refer to the complete Student object. section 7.7

For a polymorphic base class, provide a virtual destructor. Deleting a derived object through a base pointer without one is undefined behavior; in the Shape and Square example, it can leave the derived object’s resource unfreed. section 8.8

Listing 8.16 A base class with virtual destructor
class Point {
private:
    double x;
    double y;
public:
    Point(double x, double y) : x(x), y(y) {}
};
 
class Shape {
private:
    Point* location;
public:
    Shape(double x, double y) : location(new Point(x, y)) {}
    virtual ~Shape() { delete location;                     #1
        std::cout << "~Shape\n"; }    
    virtual double area() const = 0;
};
 
class Square : public Shape {
private:
    double* side;
public:
    Square(double side, double x, double y) : Shape(x, y),
        side(new double(side)) {}
    ~Square() { delete side;  std::cout << "~Square\n"; }
    double area() const { return *side * *side; }  // still looks weird
};
 
int main() {
    Shape* s = new Square(2.5, 0, 0);  // place at origin
    std::cout << s->area() << '\n';
    delete s;
    return 0;
} 

The virtual Shape destructor allows deletion through a Shape pointer to run the Square destructor as well. section 8.8

Exceptions

Throw an exception by value and catch it by reference. Catching a derived exception as const std::exception& preserves the derived what() behavior and avoids a separate copy for the catch parameter. section 10.9

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

How deep it goes
Explains virtual dispatch, slicing, destruction, and exception handling through contrasting C++ examples.
Examples
Contrasts Square and Horse inheritance with a Moveable interface and uses Person and Student to illustrate slicing.
What you can do after
Apply it in C++ by designing a shared virtual interface, preserving derived objects, and deleting them safely through base pointers.
How it connects
Connects polymorphism with inheritance, virtual functions, object slicing, destructors, and exception handling.

Also explained in

Compare how 12 books explain polymorphism →

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.