CodeTheRobot

C++ Beginner · Lesson 16 of 22

Polymorphism and virtual functions

Calling the right function through a base pointer, override and virtual destructors.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain polymorphism and virtual functions in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

A virtual function is chosen at run time from the real type of the object. Calling through a Base& or a Base* runs the derived override. Mark overrides with override so the compiler checks the signature matches.

A base class that is deleted through a base pointer must have a virtual destructor, otherwise the derived part is never cleaned up. This is the rule behind every interface class in ROS 2.

Guided lesson

Work through these steps

  1. 1.

    Read the polymorphism and virtual functions example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

class Controller {
// Base class that defines what every controller can do.
public:
// Public interface.
  virtual ~Controller() = default;
// Virtual destructor: deleting through a Controller pointer destroys the derived object properly.
  virtual double update(double error) { return 0.0; }
// A virtual function that derived classes may replace.
};
// End of the base class.
class PController : public Controller {
// A proportional controller.
public:
// Public interface.
  explicit PController(double kp) : kp_{kp} {}
// Store the gain.
  double update(double error) override { return kp_ * error; }
// override makes the compiler verify this really replaces the base function.
private:
// Hidden data.
  double kp_;
// Proportional gain.
};
// End of the derived class.
void run(Controller& c) { std::cout << c.update(2.0) << '\n'; }
// Accepts any controller; the right update() is chosen at run time.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Polymorphism and virtual functions. Expected result: 6 0

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>

class Controller {
 public:
  virtual ~Controller() = default;
  virtual double update(double error) = 0;
};

// TODO: derive PController (returns kp * error) and ZeroController (returns 0.0), both marked override

void run(Controller& c) { std::cout << c.update(3.0) << '\n'; }

int main() {
  PController p{2.0};
  ZeroController z;
  run(p);
  run(z);
  return 0;
}

Expected output

6
0
Stuck? Show the full solution (try it yourself first)
#include <iostream>

class Controller {
 public:
  virtual ~Controller() = default;
  virtual double update(double error) = 0;
};

class PController : public Controller {
 public:
  explicit PController(double kp) : kp_{kp} {}
  double update(double error) override { return kp_ * error; }

 private:
  double kp_;
};

class ZeroController : public Controller {
 public:
  double update(double) override { return 0.0; }
};

void run(Controller& c) { std::cout << c.update(3.0) << '\n'; }

int main() {
  PController p{2.0};
  ZeroController z;
  run(p);
  run(z);
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Add a PIController next to PController. Write run() that takes Controller& and call it with both. Then remove virtual from the base update() and describe what changes.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.