CodeTheRobot

C++ Beginner · Lesson 17 of 22

Abstract classes and interfaces

Pure virtual functions, interface classes, and swapping real hardware for a fake.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain abstract classes and interfaces 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 pure virtual function (= 0) has no body and makes its class abstract: you cannot create an object of it, only of a derived class that provides every pure function. An abstract class with no data is an interface.

Interfaces let application code depend on what a device does rather than which device it is. A test can pass a fake motor and the real program can pass hardware, without changing the application.

Guided lesson

Work through these steps

  1. 1.

    Read the abstract classes and interfaces 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 MotorPort {
// An interface: what the application needs from a motor.
public:
// Public interface.
  virtual ~MotorPort() = default;
// Virtual destructor for safe deletion through the interface.
  virtual bool command(double torque) = 0;
// Pure virtual: every implementation must provide it.
};
// End of the interface.
class FakeMotor : public MotorPort {
// A test double that needs no hardware.
public:
// Public interface.
  bool command(double torque) override { last_ = torque; return true; }
// Remember the command and report success.
  double last() const { return last_; }
// Let a test inspect what was commanded.
private:
// Hidden data.
  double last_{0.0};
// The most recent torque command.
};
// End of the fake.
// MotorPort port;
// Would not compile: an abstract class cannot be instantiated.

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 Abstract classes and interfaces. Expected result: 5

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 <algorithm>
#include <iostream>

class MotorPort {
 public:
  virtual ~MotorPort() = default;
  virtual bool command(double torque) = 0;
};

class FakeMotor : public MotorPort {
 public:
  // TODO: implement command(): remember the torque in last_ and return true
  double last() const { return last_; }

 private:
  double last_{0.0};
};

// TODO: write apply(MotorPort& port, double torque): limit torque to at most 5.0, then send it

int main() {
  FakeMotor fake;
  apply(fake, 8.0);
  std::cout << fake.last() << '\n';
  return 0;
}

Expected output

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

class MotorPort {
 public:
  virtual ~MotorPort() = default;
  virtual bool command(double torque) = 0;
};

class FakeMotor : public MotorPort {
 public:
  bool command(double torque) override {
    last_ = torque;
    return true;
  }
  double last() const { return last_; }

 private:
  double last_{0.0};
};

bool apply(MotorPort& port, double torque) { return port.command(std::min(torque, 5.0)); }

int main() {
  FakeMotor fake;
  apply(fake, 8.0);
  std::cout << fake.last() << '\n';
  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

Define a MotorPort and FakeMotor. Write an application function that takes MotorPort& and clamps torque to 5 N·m. Test it with FakeMotor and confirm the last command.

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.