Access Specifiers in C++

Access Specifiers in C++ with Examples

In this article, I am going to discuss Access Specifiers in C++ with Examples. Please read our previous article where we discussed How C++ Constructors are called in Inheritance with Example. Access Specifiers are also called Access Modifiers. The Access Specifiers of C++ are public, private, and protected.

Why Access Specifiers in C#?

Access Specifiers are basically used to implement Data Hiding. Data Hiding in C++ Refers to restricting access to data members of a class from outside the class. This is required when we don’t want other functions and classes to tamper with our class data. However, it is also important to make some member functions accessible so that the hidden data can be manipulated indirectly. This is where Access Specifiers come into the picture. It allows us to determine which class members are accessible to other classes and functions, and which class members are restricted from access.

Access Specifiers in C++

Now let us understand access specifiers in C++ with Examples. So, what are Access Specifiers in C++? public, private, and protected are access specifiers. What is the effect of all these access specifiers? Why do we have three types of Access Specifies in C++? Let us learn about them.

Example to Understand the need for Access Specifiers in C++:

Let us understand this with an example. Let us say we have a class called Base as follows.

class Base
{
    private:
        int a;
    protected:
        int b;
    public:
        int c;

    void funBase()
    {
        a = 10;
        b = 20;
        c = 30;
    }
};

This is the Base class. Here, we have declared three data members and one member function inside the class. First, integer a is declared as private, integer b is declared as protected and integer c is declared as public. Then we have publically defined a function funBase of return type void. Inside this function, we have assigned some values to variables a, b and c.

So, this Base class has all types of members that is public, protected, and private. Then we have a function funBase which is accessing all these members. Accessing means trying to read or write. In this example, funBase function is writing the values. The data members a, b and c are the members of the same class so funBase function can access all these members.

So, the point that you need to remember is within the same class, all the private, protected and public members are accessible. Now let us create the object of the Base class inside the main function as follows.

int main(){
    Base x;
    x.a = 21;
    x.b = 22;
    x.c = 23;
}

In the main function, we have created an object x of the Base class. So, an object x will be created with 3 data members. Then we are trying to write the values of a, b, and c through object x. So, can we access all these variables? No. Upon object, we cannot access private members and protected members. But we can access public members. So, we can access only public members upon an object. For a better understanding, please have a look at the below image.

Example to Understand the need for Access Specifiers in C++

So, c is the only variable that we can access through object x of class Base. Because we have defined c as public in class Base. When we create an object of a class, we cannot access all members except public members.

Now let us look at what happens in their derived class. So, let us create a class called Derived which is inheriting from the class Base as follows:

class Derived : Base
{
    public:
        fundDerived ()
        {
            a = 1;
            b = 2;
            c = 3;
        }
};

This is our Derived class which is inheriting from the Base class. Inside this class, we have written a function called fundDerived as public. Now when we say that the Derived class is inheriting from the Base class. So, we will get everything present in the Derived class which is already present in the Base class. So, all the members of the Base class will be available in the Derived class. This is what we understood from Inheritance.

Next, we have assigned some values to a, b, and c inside the function fundDerived. So, can we access these members in the Derived class? No, the Derived class cannot access the private members of the Base class. The Derived class can access only public and protected members of the Base class in C++. For a better understanding, please have a look at the below image.

Access Specifiers in C++ with Examples

So, function fundDerived cannot access a variable but it can access b and c members. The Derived class cannot access private members of its base class. The point that you need to remember is private members are available but not accessible to derived classes.

Now, look at all these things. We have a class Base with private, public, and protected members. These all are accessible in the Base class. But in the Derived class, private members are not accessible but public and protected members are accessible. And on an object, only public members are accessible.

What is the idea behind this limitation?

Let us understand this with some real-time examples and try to understand why such rules are framed in object-oriented programming. Let us understand why the public, protected, and private are there. So let us take an example and understand this one. Suppose our company has designed a car.

My Design:

Access Specifiers in C++ with Examples

This is my car. You also have an automobile company and you want to borrow technology from my company. So, this happens like one company borrows technology from another company. These companies will give you some designs to other companies so that they can take that design and extend it and they can manufacture their own car.

Your Design:

Access Specifiers in C++ with Examples

So, your company is borrowing the design from my company. So, you have taken this design and you have designed your own car. This car is having same features as my design plus some extra features. So, your car is inheriting from my car.

When I give you my design, I give you the permission to make any modifications or any changes you want except don’t modify this property. That means I can give you permission on a few things and I can restrict you from a few things. So, when I want to restrict something, I should make them private and when I allow you to access something or modify something in my design then I can make them protected or public.

So, I can access everything in my design that is I can access public, private as well as protected members. But when you have taken my design then you are only allowed to access protected and public members. You cannot access private members. I have given you the complete design and said that you should not touch this one. You should not modify this one.

Suppose my company has manufactured a car. And one of the customers has purchased this car. So, this car is an object of my design. Design is nothing but a blueprint. So, I have manufactured a car and sold it to a person and that person can access only public members. He cannot access protected and private members. So, I have allowed only public members to be accessible by the customer. He cannot access everything.

For example, when you buy a car, you can see a lot of things having sealed on it i.e. “Don’t open this”. You can use steering, gearbox, accelerator, brake, etc., but don’t open anything which is sealed. So, for everything inside a car that is private to the customer, the company will take that responsibility.

In other engineering, if anything needs repair then the company will repair it and give it. In software, there is nothing like repair. So, we don’t allow the user to access everything we allow only public members to be accessible. So, this is the idea behind access specifiers and per your requirement, you can make them public, private, or protected.

Private, Protected, and Public in C++

Now let us summarize all these things in a single table for better understanding.

Private, Protected, and Public in C++

So, this is the summarized form of the above explanation. Now let us look at the complete program.

Example to Understand Access Specifiers in C++:
#include <iostream>
using namespace std;

class Base
{
    private:
        int a;
    protected:
        int b;
    public:
        int c;

        void funBase ()
        {
            a = 10;
            b = 20;
            c = 30;
        }
};

class Derived:public Base
{
    public:
        void funDerived ()
        {
            a = 21;
            b = 22;
            c = 23;
        }
};

int main()
{
    Base b;
    b.a = 10;
    b.b = 5;
    b.c = 20;
}
Output:

Example to Understand Access Specifiers in C++

What are Access Specifiers in C++?

In C++, the Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class members i.e. accessibility to the data members and member functions. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions. There are 3 types of access Specifiers available in C++:

  1. Public
  2. Private
  3. Protected

Note: If we do not specify any Access Modifiers for the class members then by default the Access Modifiers for the class members will be Private in C++.

Public Access Specifier in C++:

In C++, we can use the public keyword to create public members i.e. data members and member functions. When we declare the class members under the Public Access Specifier, then all those members will be available to everyone and everywhere i.e. we can access in the same class, in the derived class as well as create objects outside the class and we can also access it. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.

Let us understand Public Access Specifier in C++ with an example. In the below example the data member Radius and member function GetArea() are declared as public so they are accessible outside the class and thus were allowed access from inside the main() function.

#include <iostream>
using namespace std;
class Circle
{
    public:
        double Radius;
        double GetArea()
        {
            return 3.14 * Radius * Radius;
        }
};

int main()
{
    Circle obj;

    //Accessing public datamember outside class
    obj.Radius = 7.5;

    cout << "Radius of Circle is: " << obj.Radius << "\n";
    cout << "Area of Circle is: " << obj.GetArea ();
    return 0;
}
Output:

Public Access Specifier in C++

Private Access Specifier in C++:

In C++, we can use the private keyword to create private members i.e. data members and member functions. When we declare the class members under the Private Access Specifier, then all those members are only accessible within the class. They are not allowed to be accessed directly by any object or function outside the class. Even they are also not accessible by the derived classes. Only the member functions of the same class or the friend functions are allowed to access the private data of a class.

Let us understand this with an example. In the below example the data member Radius is declared as private and member function GetArea() is declared as public. So, from outside the class, we can access the GetArea() member function but we cannot access the private data member Radius.

#include <iostream>
using namespace std;
class Circle
{
    private:
        double Radius;
    public:
        double GetArea()
        {
            //Member function of the same class can access 
            //private data member Radius
            return 3.14 * Radius * Radius;
        }
};

int main()
{
    //Creating an object
    Circle obj;

    //Trying to access private datamember directly outside class
    obj.Radius = 7.5;

    cout << "Radius of Circle is: " << obj.Radius << "\n";
    cout << "Area of Circle is: " << obj.GetArea ();
    return 0;
}
Output:

Private Access Specifier in C++

As you can see, here we are getting a compile-time error. This is because we are not allowed to access the private data of a class directly outside the class. However, we can access the private data members of a class indirectly using the public member functions of the class as shown in the below example.

#include <iostream>
using namespace std;
class Circle
{
    private:
        double Radius;
    public:
        void GetArea(double radious)
        {
            //Member function of the same class can access 
            //private data member Radius
            Radius = radious;
            double area = 3.14 * Radius * Radius;
            cout << "Radius of Circle is: " << Radius << "\n";
            cout << "Area of Circle is: " << area;
        }
};

int main()
{
    Circle obj;
    obj.GetArea(7.5);
    return 0;
}
Output:

Private Access Specifier in C++

Protected Access Specifier in C++:

In C++, we can use the protected keyword to create protected members i.e. data members and member functions. The Protected Access Specifier is similar to the Private Access Specifier in the sense that it can’t be accessed directly outside of its class unless with the help of a friend class. The difference is that the class members declared as Protected can be accessed by any derived class of that class as well. Let us understand this with an example.

#include <iostream>
using namespace std;
//Base class
class Base
{
    // protected data members
    protected:
        int Id;
};

// Derived class from public Base class
class Derived:public Base
{
    public:
        void SetId (int id)
        {
            // Derived class is able to access the inherited
            // protected data members of Base class
            Id = id;
        }

        void DisplayId ()
        {
            cout << "Id is: " << Id << endl;
        }
};

int main()
{
    Derived obj;
    obj.SetId (81);
    obj.DisplayId ();
    return 0;
}
Output:

Protected Access Specifier in C++

In the next article, I am going to discuss IsA and HasA Relationship in C++ with Examples. Here, in this article, I try to explain Access Specifiers in C++ with Examples and I hope you enjoy this Access Specifiers in C++ with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Access Specifiers in C++”

  1. blank

    Guys,
    Please give your valuable feedback. And also, give your suggestions about the Access Specifiers in C++ concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to Access Specifiers, you can also share the same.

Leave a Reply

Your email address will not be published.