C++ Access Specifiers

If you want to learn how to access the members of a class in C++, then understanding the Access Specifiers is a must. The members of a class are private by default, therefore if you will not add any access specifier, then the specifier is private.

Types of Access Specifiers

There are three Access Specifiers in C++:

  • public
  • private
  • protected

The following is the syntax to declare access specifiers in C++:

The public Access Specifier

As the name suggests, if the access specifiers are public, the members can be accessed from outside the class easily. Let’s see the syntax:

Let us see an example to implement the public access specifier:


The private Access Specifier

If the access specifiers are private, the members cannot be accessed from outside the class. Let’s see the syntax:

As you can see above, if you won’t set any specifier, it is private by default.

Let us now see the above example and try to understand the private access specifier in C++. We will set one of the attributes to private:

The output is as follows. Displays an error since we are trying to access the width attribute, which is private:

The protected Access Specifier

If the access specifier is set protected, the protected members can be accessed from the derived/ child class. The concept of Inheritance i.e. derived and child class is discussed in the Inheritance lesson.

C++ Constructors
C++ Inheritance
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading