C++ Access Specifiers

In C++, access specifiers define the accessibility of class members (attributes and methods). They control whether class members can be accessed from outside the class or only within it. The three main access specifiers are public, private, and protected.

Types of Access Specifiers

  • Public members can be accessed from anywhere.
  • Private members cannot be accessed directly outside the class; use public methods to modify or read them.
  • Protected members are accessible in derived classes, making them useful in inheritance.

Next Topic

Next, learn about Encapsulation in C++.

  • public: Members declared as public can be accessed from anywhere in the program.
  • private: Members declared as private can only be accessed within the class itself.
  • protected: Members declared as protected can be accessed within the class and by derived classes (inheritance).

Example: Access Specifiers

#include <iostream>
using namespace std;

class Student {
public:
    string name;    // Public member

private:
    int age;        // Private member

protected:
    int rollNo;     // Protected member

public:
    void setAge(int a) {  // Public method to set private member
        age = a;
    }

    int getAge() {        // Public method to access private member
        return age;
    }

    void setRollNo(int r) { // Public method to set protected member
        rollNo = r;
    }

    int getRollNo() {        // Public method to access protected member
        return rollNo;
    }
};

int main() {
    Student s1;
    s1.name = "Alice";       // Accessing public member directly
    s1.setAge(20);           // Accessing private member via public method
    s1.setRollNo(101);       // Accessing protected member via public method

    cout << "Name: " << s1.name << ", Age: " << s1.getAge() << ", Roll No: " << s1.getRollNo() << endl;

    return 0;
}

Output

Name: Alice, Age: 20, Roll No: 101

Important Notes

  • Public members can be accessed from anywhere.
  • Private members cannot be accessed directly outside the class; use public methods to modify or read them.
  • Protected members are accessible in derived classes, making them useful in inheritance.

Next Topic

Next, learn about Encapsulation in C++.