Access specifiers


Access specifiers


C++ allows you to control access to classes, methods, and fields with the help of access specifiers.

There are three access specifiers :

  • Private
  • Public
  • Protected

Private :

Private specifier means that a data member can be accessed and processed by the member function of the class.
The private member can't be accessed by the outer class or outside this class.

When the data members are in the private access specifier then the object of that class
can't assign or modify the value directly, that is that object can't have the direct access.

eg:

class Test
{
private :
int value;
};

void main()
{
Test t;

t.value=10; //error can't access private data member
}

Note :


Friend function of the class can also accessed the private data members.
We will discuss about the friend function in detail later.

Public :

In this access specifier, data members can be accessed and processed by all the member functions and the friend function by the other classes or outside class.

Note :

When the data members are declared as public then the object of that class can assign or
modify the values . That is direct access is available to the object.

eg:

class Test
{
public :
int value;
};

void main()
{
Test t;

t.value=10; //correct
}


Protected :


Protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, but not from anywhere else. We use this access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.

We will discuss the subclasses in detal in inheritence tutorials.




     Prev                                                   NEXT

0 comments:

Post a Comment