Access Specifiers in C++

05 min read

Access modifiers are generally used to implement a feature of Object Oriented Programming known as Data Hiding. Access modifiers or Access Specifiers in a class are used to define the accessibility of the class members. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions.

There are 3 types of access modifiers available in C++:

  1. Public
  2. Private
  3. Protected

Note: If we do not specify any access modifiers for the members of the class then by default the access modifier for the members will be Private.

 

1) If a member is made private, it can be accessed only by the functions defined within the class. No other outside function can access it. But outside functions defined as friend can be allowed to access the private members.

2) If a member is made public, it can be accessed not only by the functions which are members of that class but also by other functions defined outside the class.

3) If a member is made protected, it can not only be accessible from members of their same class and from their friends class, but also from members of their derived classes.

class Rectangle
{
private:
int length;     //Here length and breadth are called data members and they can be accessed by the functions of this class
int breadth;

public:
void getdata();   //getdata and area are called as member functions
void area();
};

 

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error