Access Specifiers in C++

In a C++ language there are three types of access specifiers . They are: public private and protected.

Public: A public data can be accessed by out side of the code in which it is defined .

Private : A private data can not be accessed by outside of the code in which it is defined.

The private data can be accessed by only member function and friend function of that class.

Protected : A protected access specifier is similar to the private only difference is that it has a access to their derived classes.

Default : By default access specifier is private means when we have not specified access specifier it will be private.

Syntax for declaring a class:

Example

In the above example we have created a new class “student”.

Inside the student class we have created two private data member age & name[20] and two public member function input() & show().

Example :  write a program to add two number by using class and public data member.

Output:

Note: In the above program we have created a class “example” which hold public integer data x,y and inside the main function we create a object of class example name obj.

By using the object and (.) dot operator you can access public data member of the calss.

Note: we can create more than one object of the class. For example:

More than one object of the class:

in a C++ we can create one or more than one object of the class.

In the below example we have created two object of class “example”.

Output

Categories C++