virtual Functions and Polymorphism

Through a base-class reference, a virtual call runs the derived version; a non-virtual call does not.

C++ · beginner · 8 min · 13 steps · free

What you'll learn

virtual_functions.cpp

#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const { return 0; }
    double plain() const { return -1; }      // not virtual
    virtual ~Shape() {}
};

class Square : public Shape {
    double s;
public:
    Square(double s) : s(s) {}
    double area() const override { return s * s; }
    double plain() const { return 99; }
};

int main() {
    Square sq(3);
    Shape &ref = sq;
    double a = ref.area();     // virtual: Square's version runs
    double p = ref.plain();    // not virtual: Shape's version runs
    cout << a << " " << p << endl;
    return 0;
}

Step by step

  1. C++ runs the Square constructor to set up the new object, with s = 3.
  2. C++ runs the Shape constructor to set up the new object.
  3. Square() has finished, so its variables are gone. Shape() has finished, so its variables are gone. sq is created on the stack with the value {s: 3}.
  4. ref is a Shape& bound to a Square.
  5. area() is virtual, so the real object's version (Square) runs.
  6. area() has finished, so its variables are gone. The value it returned, 9, is stored in a.
  7. plain() is not virtual.
  8. plain() has finished, so its variables are gone. The value it returned, -1, is stored in p.
  9. It prints 9 -1.
  10. The method returns 0.
  11. The destructor ~Square() runs, because the object is going away.
  12. The destructor ~Shape() runs, because the object is going away.
  13. 9 -1.

Common mistakes

Best practices

Key takeaways

Check yourself

Base &b = derived; b.f() with f virtual runs?

Answer: Derived::f. Dynamic dispatch.

Why a virtual destructor?

Answer: So deleting through a base pointer cleans up the derived part. Otherwise only the base destructor runs.

·

More in Inheritance and Polymorphism