[oop - lec 07] access specifiers
TRANSCRIPT
Access SpecifiersMuhammad Hammad Waseem
Access Specifiers• The commands that are used to specify the access level of class
members.• These are used to enforce restrictions to members of a class.• There are three access specifiers• ‘public’ is used to tell that member can be accessed whenever you have
access to the object• ‘private’ is used to tell that member can only be accessed from a member
function• ‘protected’ to be discussed when we cover inheritance
Private Access Specifier• The private access specifier is used to restrict the use of class member within the
class.• Any member of the class declared with private access specifier can only be
accessed within the class. • It cannot be accessed from outside the class.• It is also the default access specifier.• The data members are normally declared with private access specifier.• It is because the data of an object is more sensitive.
• The private access specifier is used to protect the data member from direct access from outside the class.• These data members can only be used by the functions declared within the class.
Public Access Specifier• The public access specifier is used to allow the user to access a class
member within the class as well as outside the class. • Any member of the class declared with public access specifier can be
accessed from anywhere in the program.• The members functions are normally declared with public access
specifier.• It is because the users access functions of an object from outside the class.
• The class cannot be used directly if both data members and member functions are declared as private.
Exampleclass Student{private:char * name;int rollNo;
public:void setName(char *);void setRollNo(int);
...};
Cannot be accessed outside class
Can be accessed outside class
Exampleclass Student{...int rollNo;
public:void setRollNo(int aNo);
};int main(){Student aStudent;aStudent.SetRollNo(1);
}
Default Access Specifiers• When no access specifier is mentioned then by default the member is
considered private member
class Student{char * name;int RollNo;
};
class Student{private:char * name;int RollNo;
};
Exampleclass Student{char * name;int RollNo;void SetName(char *);
};Student aStudent;aStudent.SetName(Ali);
Error
Exampleclass Student{char * name;int RollNo;public:void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);