CodeTheRobot

C++ Beginner · Lesson 14 of 22

Encapsulation

Private data, a small public interface, and class invariants.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain encapsulation 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

Encapsulation means an object's data is private and can only be changed through methods that keep it valid. The rule that must always be true for a valid object is called its invariant, for example 'the joint angle is always inside its limits'.

A small public interface is easy to test and lets you change the inside later without breaking callers. Expose behaviour (move_to) rather than raw data (a public angle variable).

Guided lesson

Work through these steps

  1. 1.

    Read the encapsulation 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 Joint {
// A joint that guarantees its angle stays inside the limits.
public:
// The public interface starts here.
  Joint(double low, double high) : low_{low}, high_{high} {}
// Store the limits once, at construction.
  bool move_to(double angle) {
// The only way to change the angle.
    if (angle < low_ || angle > high_) return false;
// Refuse targets that would break the invariant.
    angle_ = angle;
// Accept a valid target.
    return true;
// Tell the caller it worked.
  }
// End of move_to.
  double angle() const { return angle_; }
// Read-only access to the current angle.
private:
// Nobody outside the class can touch the data below.
  double low_, high_;
// The allowed range.
  double angle_{0.0};
// Current angle, starting inside the range.
};
// End of the class.

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 Encapsulation. Expected result: true false 1

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 Joint {
 public:
  Joint(double low, double high) : low_{low}, high_{high} {}
  // TODO: write move_to(angle): refuse angles outside [low_, high_]; otherwise store and return true
  double angle() const { return angle_; }

 private:
  double low_, high_;
  double angle_{0.0};
};

int main() {
  Joint j{-1.57, 1.57};
  std::cout << std::boolalpha << j.move_to(1.0) << '\n' << j.move_to(5.0) << '\n' << j.angle() << '\n';
  return 0;
}

Expected output

true
false
1
Stuck? Show the full solution (try it yourself first)
#include <iostream>

class Joint {
 public:
  Joint(double low, double high) : low_{low}, high_{high} {}
  bool move_to(double angle) {
    if (angle < low_ || angle > high_) return false;
    angle_ = angle;
    return true;
  }
  double angle() const { return angle_; }

 private:
  double low_, high_;
  double angle_{0.0};
};

int main() {
  Joint j{-1.57, 1.57};
  std::cout << std::boolalpha << j.move_to(1.0) << '\n' << j.move_to(5.0) << '\n' << j.angle() << '\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

Write a Joint class with limits, a move_to that rejects illegal targets, and a const angle(). Write a test that tries a target above the limit and confirms the angle is unchanged.

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.