C++ Access Modifiers


Introduction

In C++, access modifiers are used to define the visibility of class members (variables and functions). They help control how and where the members of a class can be accessed, ensuring that the internal details of a class are protected from outside interference and misuse. The primary access modifiers in C++ are public, private, and protected.


1. What Are Access Modifiers?

Access modifiers in C++ determine the accessibility of class members. These modifiers are used to set the visibility and accessibility of the class's attributes and methods from outside the class.

  • Public members are accessible from anywhere.
  • Private members are accessible only within the class itself.
  • Protected members are accessible within the class and by derived classes.

2. Types of Access Modifiers

1. Public Access Modifier

When a class member is declared as public, it can be accessed from anywhere in the program. Public members are part of the class’s interface, meaning they define how an object of the class can interact with other parts of the program.

Syntax:

class ClassName {
public:
    int publicVar;
    void publicMethod() {
        // Public method code
    }
};

Example of Public Access:

#include <iostream>
using namespace std;

class Car {
public:
    string model;
    int year;

    void displayInfo() {
        cout << "Car Model: " << model << ", Year: " << year << endl;
    }
};

int main() {
    Car car1;
    car1.model = "Toyota";
    car1.year = 2020;

    // Accessing public method
    car1.displayInfo();  // Output: Car Model: Toyota, Year: 2020

    return 0;
}

Explanation:

  • model, year, and the displayInfo() method are public, so they can be accessed directly from outside the class.

2. Private Access Modifier

When a class member is declared as private, it is accessible only within the class itself. Private members cannot be accessed directly from outside the class. They are typically used to store data that should not be directly modified from outside the class.

Syntax:

class ClassName {
private:
    int privateVar;

public:
    void setPrivateVar(int value) {
        privateVar = value;  // setter method
    }

    int getPrivateVar() {
        return privateVar;  // getter method
    }
};

Example of Private Access:

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;

public:
    // Setter method to modify private variable balance
    void setBalance(double amount) {
        if(amount >= 0)
            balance = amount;
        else
            cout << "Invalid balance" << endl;
    }

    // Getter method to access private variable balance
    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.setBalance(500.0);  // Setting balance using setter
    cout << "Account balance: " << account.getBalance() << endl;  // Getting balance using getter

    // Uncommenting the line below will give an error, as balance is private
    // cout << account.balance << endl;

    return 0;
}

Explanation:

  • The balance variable is private, so it cannot be accessed directly outside the class.
  • Getter and setter methods (getBalance() and setBalance()) are provided to access and modify the balance safely.

3. Protected Access Modifier

When a class member is declared as protected, it is accessible within the class and its derived (child) classes. Protected members are not accessible outside the class hierarchy.

Syntax:

class ClassName {
protected:
    int protectedVar;

public:
    void setProtectedVar(int value) {
        protectedVar = value;
    }
};

Example of Protected Access:

#include <iostream>
using namespace std;

class Animal {
protected:
    string species;

public:
    void setSpecies(string s) {
        species = s;
    }
};

class Dog : public Animal {
public:
    void displaySpecies() {
        cout << "This dog is a: " << species << endl;  // Accessing protected member
    }
};

int main() {
    Dog dog1;
    dog1.setSpecies("Golden Retriever");
    dog1.displaySpecies();  // Output: This dog is a: Golden Retriever

    return 0;
}

Explanation:

  • The species variable is protected, meaning it is accessible in the Animal class and its derived class Dog.
  • The Dog class can access and modify the species member of the Animal class.

3. Access Modifiers and Inheritance

When using inheritance, access modifiers affect how the members of a base class are inherited in the derived class.

  • Public members of a base class remain public in the derived class.
  • Private members of a base class are not inherited directly by the derived class, meaning they cannot be accessed directly, but they can be accessed via public or protected getter/setter functions.
  • Protected members of a base class remain protected in the derived class.

Example 4: Access Modifiers with Inheritance

#include <iostream>
using namespace std;

class Base {
public:
    int publicVar;
protected:
    int protectedVar;
private:
    int privateVar;

public:
    Base() {
        publicVar = 10;
        protectedVar = 20;
        privateVar = 30;
    }
};

class Derived : public Base {
public:
    void display() {
        cout << "Public Variable: " << publicVar << endl;        // Accessible
        cout << "Protected Variable: " << protectedVar << endl;  // Accessible
        // cout << "Private Variable: " << privateVar << endl;   // Not Accessible (Error)
    }
};

int main() {
    Derived derivedObj;
    derivedObj.display();
    
    return 0;
}

Output:

Public Variable: 10
Protected Variable: 20

Explanation:

  • The publicVar and protectedVar are accessible in the derived class, but the privateVar is not, as it is private in the base class.
  • If privateVar needs to be accessed, you would use a getter function in the base class.

4. Default Access Modifier in C++

In C++, the default access modifier for class members depends on whether the class is a struct or a class:

  • In a class, the default access modifier is private.
  • In a struct, the default access modifier is public.

Example 5: Default Access in Struct and Class

#include <iostream>
using namespace std;

class MyClass {
    int privateVar;  // private by default
};

struct MyStruct {
    int publicVar;  // public by default
};

int main() {
    // MyClass privateVar is not accessible
    // MyStruct publicVar is accessible
    MyStruct obj;
    obj.publicVar = 10;
    cout << "Public variable in struct: " << obj.publicVar << endl;

    return 0;
}

Explanation:

  • In MyClass, the member privateVar is private by default (you cannot access it outside the class).
  • In MyStruct, the member publicVar is public by default (it can be accessed directly).