[OOP - Lec 07] Access Specifiers

HammadAli89 4,603 views 9 slides Jun 04, 2016
Slide 1
Slide 1 of 9
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9

About This Presentation

Access Specifiers


Slide Content

Access Specifiers Muhammad Hammad Wasee m

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 t o 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 .

Example class Student{ private: char * name; int rollNo; public: void setName(char *); void setRollNo(int); ... }; Cannot be accessed outside class Can be accessed outside class

Example class 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 ; };

Example class Student { char * name; int RollNo; void SetName(char *); }; Student aStudent; aStudent.SetName(Ali); Error

Example class Student { char * name; int RollNo; public: void setName(char *); }; Student aStudent; aStudent.SetName(“Ali”);