Access Specifiers In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Access Specifiers In C++

Access Specifiers In C++

BLUF: Mastering Access Specifiers In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Access Specifiers In C++

C++ is renowned for its efficiency. Learn how Access Specifiers In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, access specifiers play a crucial role in determining the visibility of class members (like variables and functions) from external sources. They are essential for encapsulation as they control access to internal data and implementation specifics, preventing unauthorized or unintended manipulation.

Access modifiers enable us to manage access to particular elements of the class externally. They serve to safeguard data from accidental alterations or misuse. These modifiers guarantee that only the class sections intended for external usage are accessible, keeping confidential and internal information concealed. Moreover, they contribute to bolstering security, resilience, and code compartmentalization.

Types of Access Specifiers

In C++, access specifiers come in three main types, which assist in determining the accessibility of class members:

Here, we will examine these access modifiers individually.

Public Access Specifier

In C++, the public access specifier is primarily employed to indicate that a class member is accessible from both inside and outside the class. This implies that any function or object has the ability to reach the public members of the class. The public members of a class are predominantly used to depict the class interface.

By specifying a member function with the public keyword, it signifies that there are no limitations on its accessibility. This is frequently employed when data or functions need to be conveniently shared or accessed by other sections of the code.

Syntax

It has the following syntax:

Example

class Class_Name {

public:

    // Public data members

    int public_var;

    // Public member functions

    void publicFunc();

};

C++ Public Access Specifier Example

Let's consider an example to demonstrate the public access modifier in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Book_Store   //base class

{

public:

    string booktitle;

    void showTitle() 

    {

        cout << "The Title of Book is: " << booktitle << endl;

    }

};

int main()  //main function

{

    Book_Store book;  //object

    book.booktitle = "The C++ Programming Guide";

    book.showTitle();

    return 0;

}

Output:

Output

The Title of Book is: The C++ Programming Guide

Explanation:

In this instance, the public access modifier is employed by the BookStore class to grant unrestricted access to its booktitle property and the showTitle function. Within the main routine, a value is set to the booktitle and the method is called to exhibit it.

Private Access Specifier

In C++, the private access specifier is primarily employed to limit access to the class members. When a member function is defined as private (using the private keyword), it is only accessible and modifiable by other member functions within the same class. This prevents direct access by any external function or object. The private specifier ensures data encapsulation, enabling us to safeguard the internal state of an object from inadvertent or unauthorized alterations.

When incorporating private members within a program, a class can encapsulate its internal workings, revealing essential information and operations to external entities through public methods. This approach aids in preserving data integrity and managing the class's functionality effectively.

Syntax

It has the following syntax:

Example

class Class_name {

private:

    int privateVar;    // Private data members

    void private_Func();     // Private member functions

};

C++ Private Access Specifier Example

Let's consider a scenario to demonstrate the private access modifier in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class BankAccount   //base class

{

private:  //private specifiers

    double balance;

public:

    string account_holder_name;

    void setBalance(double amount) 

    {

        balance = amount;

        cout << "The Account Holder name is: " << account_holder_name << "\nThe remaining amount is: $" << balance << endl;

    }

};

int main()   //main function

{

    BankAccount a;  //object

    a.account_holder_name = "john";

    a.setBalance(1380.27);

    return 0;

}

Output:

Output

The Account Holder name is: John

The remaining amount is: $1380.27

Explanation:

In this instance, we showcase the implementation of the private access modifier, which restricts direct manipulation of the balance variable, ensuring it can only be modified and accessed through the setBalance public method.

Protected Access Specifier

In C++, the protected access specifier is primarily employed to indicate that a class member is accessible within the class and by its derived classes. This implies that any function or object external to the class is restricted from accessing the protected members. These protected members usually embody the class's implementation details that need to be available to its derived classes.

Syntax

It has the following syntax:

Example

class Class_name {

protected:

    // Protected data members

    int protectedVar;

    // Protected member functions

    void protected_Func();

};

C++ Protected Access Specifier Example

Let's consider a scenario to demonstrate the protected access modifier in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Employee   //Base class

{

protected:  

    double salary;

public:

    string name;

    void setSalary(double amount) 

    {

        salary = amount;

    }

};

class Manager : public Employee   //derived class

{

public:

    void Display() 

    {

        cout << "The Manager Name is: " << name << "\nThe Salary is: $" << salary << endl;

    }

};

int main()   //main function

{

    Manager m;

    m.name = "John";

    m.setSalary(95000.00);

    m.Display();

    return 0;

}

Output:

Output

The Manager Name is: John

The Salary is: $95000

Explanation:

In this instance, we illustrate the application of access modifiers. Here, we showcase an Employee class featuring a protected attribute for salary and a public attribute for name. The class includes a setSalary function for updating the salary value. Subsequently, the Manager class inherits from the Employee class and accesses the protected salary attribute directly within its Display function. Within the main routine, we instantiate a Manager object, specify the name and salary, and display the relevant details.

Access Modifiers in C++

Here is a table displaying the access specifiers in C++.

Access Specifiers Same Class Derived Class Outside Class
Public Access Specifier Yes Yes Yes
Private Access Specifier Yes No No
Protected Access Specifier Yes Yes No

Conclusion

In summary, access modifiers are essential principles in object-oriented programming because they regulate the accessibility and manipulation of class components. These modifiers play a crucial role in encapsulation, which is vital for safeguarding data, promoting modular design, and facilitating code upkeep.

C++ Access Specifiers MCQs:

1) Which of the following access specifiers allows access to members from outside the class?

  • private
  • protected
  • public
  • static

2) In C++, what is the default access specifier for class members?

  • private
  • static
  • public
  • protected

3) Which of the following access specifiers only enables access to the class and its derivative classes?

  • public
  • private
  • static
  • protected

4) What happens if we try to access a private member from outside the class in C++?

  • It will work normally
  • It will issue a warning
  • It will result in a compile-time error
  • It will switch to public

5) Which of the following access specifiers is the least accessible?

  • public
  • private
  • protected
  • virtual

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience