๐ŸŽ“ A1Learner
๐Ÿ”

C++ Encapsulation

Encapsulation is keeping data private and letting methods guard it. A guarding method can check a new value before the data changes.

A setter and a getter

The balance member is private. The setter stores 50, and the getter returns it for printing.

#include <iostream>

class Wallet {
private:
  int balance = 0;
public:
  void setBalance(int amount) {
    balance = amount;
  }
  int getBalance() {
    return balance;
  }
};

int main() {
  Wallet w;
  w.setBalance(50);
  std::cout << w.getBalance() << std::endl;
  return 0;
}

A setter refuses a bad value

The setter stores a value only when the value is not negative. The attempt to set -20 leaves the balance at 50.

#include <iostream>

class Wallet {
private:
  int balance = 0;
public:
  void setBalance(int amount) {
    if (amount >= 0) {
      balance = amount;
    }
  }
  int getBalance() {
    return balance;
  }
};

int main() {
  Wallet w;
  w.setBalance(50);
  w.setBalance(-20);
  std::cout << w.getBalance() << std::endl;
  return 0;
}

Example

#include <iostream>

class Temperature {
private:
  int degrees = 0;
public:
  void setDegrees(int value) {
    degrees = value;
    if (degrees < 0) {
      degrees = 0;
    }
  }
  int getDegrees() {
    return degrees;
  }
};

int main() {
  Temperature t;
  t.setDegrees(20);
  std::cout << t.getDegrees() << std::endl;
  t.setDegrees(-4);
  std::cout << t.getDegrees() << std::endl;
  return 0;
}

Key points

  • Encapsulation keeps the data of a class private.
  • A setter is a method that sets a private value.
  • A getter is a method that returns a private value.
  • A setter can check a value before it stores the value.
  • A setter can refuse a value that breaks a rule.
  • Code outside the class uses the setter and getter instead of the data itself.

In this example, the Temperature class keeps its degrees member private. The setter stores 20 first, and the getter prints 20. The setter then takes -4 and clamps the stored value to 0, so the second print shows 0.

Note

The private data changes only through methods the class provides.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

Why does a class keep its balance private and provide a setter?