๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

C++ Access Specifiers

An access specifier is a label that controls who can reach a member of a class. The labels public and private do that work in this lesson.

A public method reads a private member

The balance member is private. The public show method can reach it and prints it.

#include <iostream>

class Account {
private:
  int balance = 100;
public:
  void show() {
    std::cout << balance << std::endl;
  }
};

int main() {
  Account a;
  a.show();
  return 0;
}

Direct access to a private member fails

This program tries to print a private member from main. The compiler refuses the program and reports the line below.

#include <iostream>

class Account {
private:
  int balance = 100;
public:
  void show() {
    std::cout << balance << std::endl;
  }
};

int main() {
  Account a;
  std::cout << a.balance << std::endl;
  return 0;
}

Example

#include <iostream>

class Vault {
private:
  int code;
public:
  Vault(int c) {
    code = c;
  }
  int readCode() {
    return code;
  }
};

int main() {
  Vault v(4321);
  std::cout << v.readCode() << std::endl;
  return 0;
}

Key points

  • public: opens the members listed under it to all code.
  • private: limits the members listed under it to methods of the same class.
  • Code in main cannot reach a private member directly.
  • A public method can reach a private member of its own class.
  • A public method can share a private value in a safe way.

In this example, the Vault class keeps its code member private. The constructor stores the value passed at creation. The public readCode method returns that value, and main prints the result.

Note

A member of a class is private until a label opens it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which label keeps a member reachable only by methods of the same class?