Public Private Protected Access Specifier Explain With Example

Access Specifiers in C++, Public Private Protected Access Specifier Explain With Example


Three Access Specifiers :- 


Public :- 


•       Any member declared under this specifier is Accessible from Outside the class, by using  
       the object of the Class.
•       The Public members of a Class get Inherited completely to the Child Classes.
•       The keyword  “ public : “ is used.
•       Syntax :-
Class definition
{            public :
declarations or definitions
                } ;
•       Example :-
class A
{           public :
    int a;
} ;
main()
{            A  oba ;
    oba . a = 10 ; // we have set the value of variable  ‘ a ‘ in object  ‘ oba ‘ to 10
}
      

Private :-

•       Any member declared under this specifier is Not Accessible from Outside the Class.
•      The Private members are accessible to only the Member Functions and Friend Functions  
       in the Class.
•       The Private members of a Class Never get Inherited to the Child Classes.
•       The keyword  “ private : “ is used.
•       Syntax :-
Class definition
{           private :
declarations or definitions
                } ;
•       Example :-
class A
{           private :
    int a;
    public :
    void fill ( )
    {   cin >> a ;
    }
} ;
main()
{
    A  oba ;
//    oba . a = 10 ; //  invalid as  ‘ a ‘ is private member.
    oba . fill ( ) ; //  valid as  fill ( )  is a public member.
}
    

Protected :- 


•      Any member declared under this specifier is Not Accessible from Outside the class, by using the object of the Class.
•      The Protected members of a Class get Inherited completely to the Child Classes and they maintain their Protected visibility in the child Class.
•      The Protected members are accessible to only the Member Functions and Friend Functions in the Class.
•      The keyword  “ protected : “ is used.
•       Syntax :-
Class definition
{            protected :
declarations or definitions
                } ;
•       Example :-
class A
{           protected :
    int a;
    public :
    void fill ( )
    {   cin >> a ;
                                                            }
                        } ;
main()
{            A  oba ;
//    oba . a = 10 ; //  invalid as  ‘ a ‘ is protected member.
    oba . fill ( ) ; //  valid as  fill ( )  is a public member.
}


Labels: