ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Access Modifiers
    Object Oriented ProgrammingTopic 6 of 24

    Access Modifiers

    7 minread
    1,271words
    Intermediatelevel

    Access Modifiers in C++

    In C++, access modifiers are keywords that determine the visibility and accessibility of class members (data members and member functions). These modifiers help in enforcing data encapsulation, one of the fundamental principles of Object-Oriented Programming (OOP). Access modifiers define how and where the members of a class can be accessed, ensuring proper control over an object’s state and behavior.

    The three primary access modifiers in C++ are:

    1. Public
    2. Private
    3. Protected

    These modifiers are used to specify the accessibility level of the members (variables or functions) of a class. Additionally, C++ provides a concept called default access for classes and structs.


    1. Public Access Modifier

    The public access modifier allows members of a class to be accessed from anywhere: inside the class, from outside the class, and from derived classes. Public members are the most accessible, as they have no access restrictions.

    Syntax:

    class ClassName {
    public:
        // Public members can be accessed from anywhere
        int publicVar;
        void publicMethod() {
            // some code
        }
    };
    

    Example:

    #include <iostream>
    using namespace std;
    
    class Car {
    public:
        string brand;
        int year;
    
        void displayDetails() {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1;
        car1.brand = "Toyota";   // Public members can be accessed directly
        car1.year = 2020;
        car1.displayDetails();   // Calling public method
        return 0;
    }
    

    Explanation:

    • The variables brand and year, along with the method displayDetails(), are public and can be accessed directly from outside the class (i.e., in the main() function).

    2. Private Access Modifier

    The private access modifier restricts the access of class members to only within the class itself. Private members cannot be accessed directly from outside the class. To access or modify these members, you must use public getter and setter methods (also known as accessors and mutators).

    Syntax:

    class ClassName {
    private:
        // Private members can only be accessed within the class
        int privateVar;
        void privateMethod() {
            // some code
        }
    };
    

    Example:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        int year;
    
    public:
        void setDetails(string b, int y) {
            brand = b;  // Private members can be accessed inside the class
            year = y;
        }
    
        void displayDetails() {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1;
        car1.setDetails("Honda", 2022);  // Accessing private members via public method
        car1.displayDetails();
        
        // car1.brand = "Toyota";  // Error: Cannot access private member 'brand'
        // car1.year = 2023;  // Error: Cannot access private member 'year'
        
        return 0;
    }
    

    Explanation:

    • The variables brand and year are private. They cannot be accessed directly from the main() function.
    • The public method setDetails() allows modifying the private members.
    • Attempting to access car1.brand or car1.year directly outside the class would result in a compilation error.

    3. Protected Access Modifier

    The protected access modifier is similar to private, with one key difference: protected members can be accessed by derived classes (subclasses), but not by outside code (not even from the main() function). This is useful in inheritance, where you want to restrict direct access but allow derived classes to access or modify certain members.

    Syntax:

    class ClassName {
    protected:
        // Protected members can be accessed within the class and derived classes
        int protectedVar;
        void protectedMethod() {
            // some code
        }
    };
    

    Example:

    #include <iostream>
    using namespace std;
    
    class Car {
    protected:
        string brand;
        int year;
    
    public:
        Car(string b, int y) : brand(b), year(y) {}
    };
    
    class SportsCar : public Car {
    public:
        SportsCar(string b, int y) : Car(b, y) {}  // Accessing protected members from base class
    
        void displayDetails() {
            cout << "Brand: " << brand << ", Year: " << year << endl;  // Accessing protected members
        }
    };
    
    int main() {
        SportsCar car1("Ferrari", 2021);
        car1.displayDetails();
        
        // car1.brand = "Porsche";  // Error: Cannot access protected member 'brand'
        // car1.year = 2022;  // Error: Cannot access protected member 'year'
    
        return 0;
    }
    

    Explanation:

    • The SportsCar class, which inherits from Car, can access the protected members (brand and year) of the Car class.
    • However, these members are still not accessible directly in the main() function because they are not public.
    • The derived class SportsCar has access to the protected members of the base class Car, but outside access is restricted.

    Default Access Modifier for Classes and Structs

    • Class: By default, members of a class are private if no access modifier is specified.

      class MyClass {
          // Members are private by default
          int privateVar;  // private
      };
      
    • Struct: By default, members of a struct are public. This is the key difference between a struct and a class in C++.

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

    Access Control Summary:

    Access Modifier Accessibility When to Use
    Public Accessible from anywhere (inside and outside the class) Use when you want a member to be freely accessible from anywhere.
    Private Accessible only within the class itself Use to protect the internal state of the object from external manipulation.
    Protected Accessible within the class and derived classes Use when you want to allow derived classes to access the base class's members but restrict external access.

    Example Demonstrating All Access Modifiers:

    #include <iostream>
    using namespace std;
    
    class Person {
    private:
        string name;   // Private: Cannot be accessed directly from outside
        int age;       // Private: Cannot be accessed directly from outside
    
    protected:
        string address;  // Protected: Can be accessed by derived classes
    
    public:
        Person(string n, int a, string addr) : name(n), age(a), address(addr) {}
    
        void displayDetails() {
            cout << "Name: " << name << ", Age: " << age << ", Address: " << address << endl;
        }
    
        void setName(string n) {
            name = n;  // Private member can be accessed within the class
        }
    
        void setAge(int a) {
            age = a;  // Private member can be accessed within the class
        }
    };
    
    class Employee : public Person {
    public:
        Employee(string n, int a, string addr) : Person(n, a, addr) {}
    
        void displayAddress() {
            cout << "Address: " << address << endl;  // Accessing protected member from derived class
        }
    };
    
    int main() {
        Person p("John", 30, "123 Main St");
        p.displayDetails();
    
        // p.name = "Jane";  // Error: Cannot access private member 'name'
        // p.age = 25;  // Error: Cannot access private member 'age'
    
        Employee e("Alice", 28, "456 Oak St");
        e.displayDetails();
        e.displayAddress();
    
        // e.address = "789 Pine St";  // Error: Cannot access protected member 'address'
        return 0;
    }
    

    Summary of Access Modifiers

    • Public members are accessible from anywhere.
    • Private members can only be accessed within the class and cannot be accessed directly from outside.
    • Protected members are accessible within the class and by derived classes, but not from outside the class.
    • C++ defaults to private access for class members and public access for struct members.

    Access modifiers are essential for encapsulating data and ensuring that objects maintain integrity and adhere to the principles of information hiding in OOP. They help manage how the data is exposed or hidden from other parts of the program.

    Previous topic 5
    Constructors and Destructors
    Next topic 7
    Const vs Non-Const Functions

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,271
      Code examples0
      DifficultyIntermediate