Site icon Learn C++

Learn about Access Specifiers in C++ Classes

Object-Oriented Programming is a way to integrate with objects which can contain data in the form (attributes or properties of objects), and code blocks in the form of procedures (methodsfunctions of objects). These attributes and methods are variables and functions that belong to the class, they are generally referred to as class members.

Think that you have a class and you have integers, floating numbers, strings, and some methods. And maybe you have some attributes or methods that you don’t want to be seen by other classes or functions. Maybe you have a class in a dynamic library and you want to make some of them visible to developers, and you want to hide some of them. If you are asking, how I can make visible and hidden members in classes, C++ is a great programming language with very specific features. Access Specifiers are the statements used for this situation.

The Access Specifiers are one of the important parts of Classes, and they are used before you define your attributes (properties) or methods (functions). Access specifiers use used to define how the members (attributes and methods) of a class can be accessed. All the attributes and methods listed after these Access Specifiers have the same access. Thus, you can define class members as a public member, or private member, or a protected member.

In C++, mostly there are 3 Access Specifiers in Classes, these are :

in addition to these, there might be specific Access Specifiers, for example,

A general class example with all public, private, and protected sections, can be given as below,

[crayon-66224592e7207798680473/]

What happens if I don’t use an Access Specifier? Can we create a class without any Access Specifier? The answer is yes, we don’t need to use, but you should know that all the members of that class will be private.

[crayon-66224592e720f462606034/]

Here above all members i, j, f, g, name are private.

For example, let’s define a THuman Class for human, name will be public and age and weight will be private, Here is the THuman class with private and public members,

[crayon-66224592e7211562858405/]

We can also add some protected members that can’t be accessed from outside the class. However, they can be accessed in inherited classes,

[crayon-66224592e7213017707955/]

Not that there is a possibility to access private members of a class using a public method inside the same class. This is called Encapsulation, Please read our next posts about Encapsulation to use it. Also, try to declare your class attributes as private as you can. It reduces the possibility of others or you make changes in the code or values of members. This is also needed to use Encapsulation.

Get started building powerful apps with C++Builder!

Exit mobile version