Explain Access control in C++

Access Control:

Access specifier or access modifiers are the labels that specify type of access given to members of a class. These are used for data hiding. These are also called as visibility modes. 

There are three types of access specifiers:-
1.private
2.public 
3.protected


1. Private:-
If the data members are declared as private access then they cannot be accessed from other functions outside the class. It can only be accessed by the functions declared within the class. It is declared by the key word "private".

2.Public:-
If the data members are declared public access then they can be accessed from other functions out side the class. It is declared by the key word "public".

3.Protected:-
The access level of protected declaration lies between public and private. This access specifier is used at the time of inheritance Note:-
If no access specifier is specified then it is treated by default as private
The default access specifier of structure is public where as that of a class is “private”.
Example:-
class student
{
private : int roll;
char name[30];
public:
void get_data()
{
cout<<”Enter roll number and name”:
cin>>roll>>name;
}
void put_data()
{
 cout<<”Roll number:”<<roll<<endl;
 cout<<”Name :”<<name<<endl;
 }
};

Object:- Instance of a class is called object.
Syntax: class_name object_name; 
Ex:
student s;

Accessing members:-dot operator is used to access members of class 
Object-name.function-name(actual arguments);

Ex:
s.get_data();
s.put_data();

Note:
1.If the access specifier is not specified in the class the default access specifier is private
2.All member functions are to be declared as public if not they are not accessible outside the class.

Object:
Instance of a class is called as object.

Syntax:
Class_name object name;
Example:
student s;
in the above example s is the object. It is a real time entity that can be used.

Program:-                                                
#include<iostream.h>
#include<conio.h>
class student
{
private:
int roll;
char name[20];
public:                    
void getdata ()        
{
cout<<"Enter Roll number:";   
cin>>roll;
cout<<"Enter name";
cin>>name;
}
void putdata()
{
cout<<"Roll no:"<<roll<<endl;
{
cout<<"Name:"<<name<<endl;
}
};
int main()
{
students s;
s.getdata();
s.putdata();
return 0;
}

Read more:

Md Ashraf

'KNOWLEDGE WITH ASHRAF' is the platform where you find all the type of knowledge especially on programming based. Our goal is to give you a deeper grasp of technology in specifics that will help you increase your knowledge.

Previous Post Next Post

Contact Form