Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Access Specifiers In C++ – A Quick glimpse to private, public, and protected

Last Updated on May 16, 2023 by Prepbytes

In C++, access specifiers are used to control the accessibility of class members (variables and functions) from different parts of a program. They specify the level of access that other parts of the program have to these members. C++ provides three access specifiers: public, private, and protected.

Wish to enhance your foundation skills, then why not check out our Foundation Courses designed by experienced mentors at PrepBytes.

What is Access Specifier?

  1. Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers.
  2. A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.

    class Base { 
        public:
            // public members go here
             protected:
            // protected members go here
             private:
            // private members go here
        };

How Does Access Specifiers Work in C++?

The accessibility of access specifiers in classes during inheritance is shown in Table.

Types of Access Specifier in C++:

  1. The public Members

    • Members declared as public are accessible from anywhere in the program, both within the class and outside the class.
    • They can be accessed directly by objects of the class or through member function calls.
    • Public members represent the interface of the class, exposing functionality that can be used by other parts of the program.
    • Public members are often used for methods that provide the main functionality of the class.
    #include <iostream>
    using namespace std;
    class Line {
    public:
        double length;
        void setLength( double len );
        double getLength( void );
    };
    // Member functions definitions
    double Line::getLength(void) {
        return length ;
    }
    void Line::setLength( double len) {
        length = len;
    }
    // Main function for the program
    int main() {
        Line line;
        // set line length
        line.setLength(6.0);
        cout << "Length of line : " << line.getLength() <<endl;
        // set line length without member function
        line.length = 10.0; // OK: because length is public
        cout << "Length of line : " << line.length <<endl;
        return 0;
    } 
    

    When the above code is compiled and executed, it produces the following result −

    Length of line : 6
    Length of line : 10
  2. The private Members

    • Members declared as private are only accessible from within the class itself.
    • Private members cannot be accessed directly from outside the class or through derived classes.
    • They are typically used to encapsulate implementation details and data that should not be directly modified or accessed externally.
    • Private members are only accessible through public member functions, which are responsible for enforcing proper access and maintaining class invariants.

    By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member −

    class Box {
       double width;
       public:
          double length;
          void setWidth( double wid );
          double getWidth( void );
    };

    Practically, we define data in the private section and related functions in the public section so that they can be called from outside of the class as shown in the following program.

    #include <iostream>
    using namespace std;
    class Box {
    public:
        double length;
        void setWidth( double wid );
        double getWidth( void );
    private:
        double width;
    };
    // Member functions definitions
    double Box::getWidth(void) {
        return width ;
    }
    void Box::setWidth( double wid ) {
        width = wid;
    }
    // Main function for the program
    int main() {
        Box box;
        // set box length without member function
        box.length = 10.0; // OK: because length is public
        cout << "Length of box : " << box.length <<endl;
        // set box width without member function
        // box.width = 10.0; // Error: because width is private
        box.setWidth(10.0);  // Use member function to set it.
        cout << "Width of box : " << box.getWidth() <<endl;
        return 0;
    }
    

    When the above code is compiled and executed, it produces the following result −

    Length of box : 10
    Width of box : 10
  3. The protected Members

    • Members declared as protected have a level of accessibility in between public and private.
    • Protected members are accessible within the class itself and its derived classes.
    • They are not directly accessible from outside the class or through objects of the class.
    • Protected members are often used when implementing inheritance, allowing derived classes to access and manipulate certain parts of the base class.

    Following example is similar to the above example and here width member will be accessible by any member function of its derived class SmallBox.

    #include <iostream>
    using namespace std;
     
    class Box {
       protected:
          double width;
    };
     
    class SmallBox:Box { // SmallBox is the derived class.
       public:
          void setSmallWidth( double wid );
          double getSmallWidth( void );
    };
     
    // Member functions of child class
    double SmallBox::getSmallWidth(void) {
       return width ;
    }
     
    void SmallBox::setSmallWidth( double wid ) {
       width = wid;
    }
     
    // Main function for the program
    int main() {
       SmallBox box;
     
       // set box width using member function
       box.setSmallWidth(5.0);
       cout << "Width of box : "<< box.getSmallWidth() << endl;
     
       return 0;
    }
    

    When the above code is compiled and executed, it produces the following result −

    Width of box : 5

Conclusion
Access specifiers in C++ play a crucial role in encapsulation and controlling the accessibility of class members. They allow you to define the level of access that other parts of the program have to the members of a class. The three access specifiers in C++ are public, private, and protected.

  • Public access specifier grants unrestricted access to the members from anywhere in the program.
  • The private access specifier restricts access to only within the class itself.
  • Protected access specifier allows access within the class and its derived classes.

By appropriately using access specifiers, you can enforce encapsulation, hide implementation details, and provide a clear and controlled interface to interact with the class. Access specifiers also facilitate the concept of inheritance and code reuse by defining the level of access for derived classes.

FAQs related to access specifiers in C++

Q1. Can access specifiers be applied to individual class members?
Ans. Yes, access specifiers can be applied to individual variables and functions within a class. Each member can have its own access specifier, which determines its accessibility.

Q2. Can I change the access specifier of a member in the derived class?
Ans. No, you cannot change the access specifier of a member in a derived class. The access specifier in the derived class must be the same or less restrictive than the access specifier in the base class.

Q3. What happens if I don’t specify an access specifier for a member?
Ans. If you don’t specify an access specifier explicitly, the default access specifier for class members is private.

Q4. Can I access private members of a class using friend functions?
Ans. Yes, you can declare a function as a friend of a class, granting it access to the private members of that class. Friend functions are an exception to the normal access control rules.

Q5. Can I inherit access specifiers from a base class?
Ans. Yes, the derived class inherits the access specifiers of the base class. Public members of the base class remain public in the derived class, protected members remain protected, and private members remain inaccessible.

Q6. Can access specifiers be used with structs in C++?
Ans. Yes, access specifiers can be used with structs in the same way as with classes. The only difference is that members of structs are public by default if no access specifier is specified.

Leave a Reply

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