C++ Access Specifiers

C++ Access Specifiers

Up until now, you have seen the public keyword in all of our class examples. This keyword is an access specifier.

Access specifiers determine how the members (attributes and methods) of a class can be accessed from outside the class.

In C++, there are three access specifiers:

  1. public - Members are accessible from outside the class.
  2. private - Members cannot be accessed (or viewed) from outside the class.
  3. protected - Members cannot be accessed from outside the class, however, they can be accessed in inherited classes (we will learn about this in the Inheritance chapter).

1. Public vs Private

Let's look at an example demonstrating the difference between public and private.

Access Specifiers Example

#include <iostream>
using namespace std;

class MyClass { public: // Public access specifier int x; // Public attribute

private: // Private access specifier int y; // Private attribute };

int main() { MyClass myObj;

myObj.x = 25; // Allowed (public)

// myObj.y = 50; // ERROR: Not allowed (private)

cout << "x is: " << myObj.x << "\n"; return 0; }

If you try to uncomment the line myObj.y = 50;, the compiler will throw an error because y is private. It can only be accessed by methods inside the MyClass itself.


Exercise

?

By default, all members of a class in C++ are: