codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ access specifiers and encapsulation

C++ access specifiers and encapsulation

public, private, protected.

Make data private and expose it through getters and setters, so the class controls how it changes.

Example code

#include <iostream>
using namespace std;
class Account {
private:
  int balance = 0;
public:
  void deposit(int n) { if (n > 0) balance += n; }
  int get() { return balance; }
};
int main() {
  Account a; a.deposit(50); a.deposit(-5);
  cout << a.get() << endl;
  return 0;
}

Run this code in the online editor

← C++ constructorsC++ friend functions →