CPP Tutorials

Access Modifiers in CPP: An Easy Guide


Welcome to our exploration of Access Modifiers in C++. In this article, we delve into the essential concept of access modifiers, which play an important role in controlling the visibility and accessibility of class members. We’ll uncover why access modifiers are vital for creating organized and secure code, how they help us show encapsulation, and why they contribute to good programming practices. By the end of this article, you’ll understand how access modifiers like public, private, and protected can enhance code readability, security, and maintainability. Let’s embark on this journey to demystify access modifiers and their significance in C++ programming.

What are Access Modifiers in C++?

Access modifiers in C++ are like gatekeepers that control how different parts of a class can be accessed. They determine whether certain members of a class (like variables and functions) can be used outside the class or are only accessible within the class itself. There are three main access modifiers in C++: public, private, and protected.

  • Public: Members declared as public are accessible from anywhere, both within and outside the class. This means that you can access them directly using object instances. Public members are often used to represent the interface of a class, defining what functionalities are available to the outside world.
  • Private: Private members are only accessible within the class they are declared in. This means that you can’t directly access them using object instances from outside the class. Private members are used to encapsulate the inner workings of a class and hide the implementation details.
  • Protected: Protected members are somewhat similar to private members, but they can also be accessed by derived classes (classes that inherit from the base class). This provides a level of access control that allows derived classes to use these members, while still keeping them hidden from the outside world.

Code Example:

#include <iostream>
using namespace std;

class MyClass {
    int publicVar;      // Public member variable

    int privateVar;     // Private member variable

    int protectedVar;   // Protected member variable

int main() {
    MyClass obj;
    obj.publicVar = 10;      // Accessing public member variable
    // obj.privateVar = 20;   // This will result in a compilation error
    // obj.protectedVar = 30; // This will also result in a compilation error
    cout << "Public Variable: " << obj.publicVar << endl;
    return 0;


Public Variable: 10


  • publicVar‘ is accessible directly from ‘main()‘.
  • Accessing ‘privateVar‘ or ‘protectedVar‘ causes compilation errors.
  • Access modifiers control member visibility.
  • They ensure encapsulation and class design integrity.

Why Access Modifiers in C++?

Access modifiers in C++ are like security guards for a class, controlling who can see and interact with different parts of the class. They ensure that certain variables and functions can only be used in specific ways, preventing accidental misuse and ensuring the class works as planned. Access modifiers help keep the inner details of a class hidden from the outside, making it easier to manage and maintain your code. They also play an important role in enforcing the principles of object-oriented programming, like encapsulation and data hiding, which make your code more organized, secure, and less prone to errors.

A Problem to Solve

Certainly! Let’s design a problem that can help students understand access modifiers in C++.

Problem Statement:

You have been hired by a bank to design the basic structure for a banking system. They want to ensure the safety and security of customer data. You’re tasked with designing a simple BankAccount class to showcase how you’d handle data security using access modifiers.


  1. Private Data Members:
  • accountNumber: A long integer that represents the account number.
  • balance: A double to store the current balance.
  • accountHolderName: A string to store the name of the account holder.
  • Public Methods:
    • deposit(double amount): Deposit the specified amount into the account. Display an appropriate message after depositing.
    • withdraw(double amount): Withdraw the specified amount from the account. Ensure that the account has sufficient funds before withdrawal, else display a message “Insufficient funds.”
    • displayBalance(): Display the current balance.
  • Protected Methods:
    • getAccountDetails(): Returns a string with the format: “Holder: [accountHolderName], Account Number: [accountNumber]”. This method might be useful for derived classes in the future (like savings or checking accounts) but should not be accessible directly from a BankAccount object.


  • Implement the BankAccount class adhering to the requirements mentioned above.
  • Create a simple main function to test the methods of your BankAccount class.


  • Use the private access modifier for data members.
  • Use the public access modifier for main operations methods.
  • Use the protected access modifier for methods that might be helpful for derived classes in the future.

Expected Output:

For the following operations:

  1. Create an account with an initial balance $1000.
  2. Deposit $500.
  3. Withdraw $200.
  4. Try withdrawing $1500.
  5. Display balance.

The output should be something like:

Amount $500 deposited.
Amount $200 withdrawn.
Insufficient funds.
Current balance: $1300.

Examples of Access Modifiers in C++

Example 1: private access modifier in C++:

#include <iostream>
using namespace std;

class MyClass {
    int privateVar;

    void setPrivateVar(int value) {
        privateVar = value;

    int getPrivateVar() {
        return privateVar;

int main() {
    MyClass obj;

    cout << "Private Variable Value: " << obj.getPrivateVar() << endl;

    return 0;


Private Variable Value: 42


Sure, here are the key points of the example using a private access modifier in C++:

  • The ‘privateVar‘ is a private member of the ‘MyClass‘ class.
  • The ‘setPrivateVar()‘ function allows changing the value of ‘privateVar‘.
  • The ‘getPrivateVar()‘ function retrieves the value of ‘privateVar‘.
  • In the ‘main()‘ function, an object of ‘MyClass‘ is created.
  • Using ‘setPrivateVar()‘, the private variable’s value is set to 42.
  • Using ‘getPrivateVar()‘, the value of the private variable is retrieved and printed.
  • Since ‘privateVar‘ is private, it can’t be directly accessed from outside the class.
  • This demonstrates the concept of encapsulation, where data is hidden from external access.

Example 2: Public access modifier in C++

#include <iostream>
using namespace std;

class MyClass {
    int publicVar;  // Public member variable

    void showPublicVar() {
        cout << "Value of publicVar: " << publicVar << endl;

int main() {
    MyClass obj;
    obj.publicVar = 42;  // Accessing the public variable
    obj.showPublicVar(); // Calling the public member function
    return 0;


Value of publicVar: 42


  • The code example uses the public access modifier.
  • The publicVar member variable and the showPublicVar() member function are declared under the public access specifier.
  • This allows both the variable and the function to be accessed from outside the class.
  • The publicVar is assigned a value of 42.
  • The showPublicVar() function is called to display the value of publicVar, which outputs: “Value of publicVar: 42”.

Pros and Cons of Using Access Modifiers in C++:

Controlled Access: Access modifiers provide control over which parts of a class are accessible from outside and which are not. This helps in maintaining data integrity and preventing unintended changes.Complexity: Overuse of access modifiers can lead to complex code, making it harder to understand the flow of data and behavior within the class.
Encapsulation: Access modifiers support encapsulation by allowing you to hide implementation details. You can expose only the necessary interface to users of the class, promoting a more organized and maintainable codebase.Tight Coupling: If access modifiers are not used carefully, they can lead to tight coupling between classes, making changes in one class require modifications in others as well.
Inheritance: Access modifiers play a crucial role in inheritance. They determine which members of the base class are accessible in derived classes, aiding in creating specialized derived classes with appropriate access to inherited features.Limiting Flexibility: Overly restrictive access modifiers can limit the flexibility of using a class, making it difficult to adapt or extend its functionality as requirements change.
Code Security: Access modifiers can enhance security by allowing you to restrict access to sensitive data or critical functions. This prevents unauthorized modifications and ensures data consistency.Testing and Debugging: Incorrect use of access modifiers can complicate testing and debugging processes, as you might not have direct access to certain parts of the class for verification.
Pros and Cons of Using Access Modifiers in C++:

Key Takeaways

  • Access modifiers control the visibility and accessibility of class members (variables and functions) from different parts of the program.
  • public members are accessible from anywhere in the program, including outside the class.
  • private members are only accessible from within the class itself and not from outside.
  • protected members are accessible from within the class and its derived classes.
  • Encapsulation is promoted by controlling access to class members, helping to ensure data integrity and encapsulation.
  • Access modifiers help in creating well-defined interfaces and hiding implementation details.
  • It enhances code readability, and maintainability, and prevents unauthorized access to sensitive data.
  • When designing classes, choose the appropriate access modifiers to enforce proper encapsulation and secure data handling.


In conclusion, access modifiers in C++ play a important role in controlling the visibility and accessibility of class members. Through the use of access modifiers like public, protected, and private, programmers can determine which parts of a class are accessible from different parts of the program. The public modifier allows for unrestricted access, while the protected modifier grants access to derived classes, and the private modifier restricts access to only within the class itself.

By using access modifiers effectively, programmers can achieve encapsulation, ensuring that the internal implementation details of a class are hidden from external users. This enhances code maintainability, reduces the risk of unintended modifications, and promotes modular programming. Access modifiers help in building secure and organized code structures, making the codebase more manageable and understandable for both individual developers and collaborative teams.


  • What is a fraction in C++?
    A fraction in C++ is a way of representing a part of a whole. It consists of a numerator and a denominator.
  • Why is adding fractions important in C++?
    Adding fractions is important in C++ because it’s used in various programming scenarios, such as data analysis, physics simulations, and game development.
  • How do you add fractions in C++?
    To add fractions in C++, you can write a program that takes two fractions as input, finds the least common multiple of the denominators, converts the fractions to have the LCM as the denominator, and adds the numerators.
  • What are some examples of adding fractions in C++?
    Some examples include adding the fractions 1/2 and 1/3 to get 5/6 and adding the fractions 2/3 and 3/4 to get 17/12.
  • What are the pros and cons of adding fractions in C++?
    Adding fractions in C++ can make your programs more versatile and useful. However, you need to handle the fractions correctly to avoid errors, such as making sure the denominator is not zero.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Becoming a Full Stack Developer in 2023 How to Become a Software Engineer in 2023

Adblock Detected

Please consider supporting us by disabling your ad blocker!