[oop - lec 07] access specifiers

9
Access Specifiers Muhammad Hammad Waseem

Upload: muhammad-hammad-waseem

Post on 06-Apr-2017

94 views

Category:

Education


3 download

TRANSCRIPT

Page 1: [OOP - Lec 07] Access Specifiers

Access SpecifiersMuhammad Hammad Waseem

Page 2: [OOP - Lec 07] Access Specifiers

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

Page 3: [OOP - Lec 07] Access Specifiers

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.

Page 4: [OOP - Lec 07] Access Specifiers

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.

Page 5: [OOP - Lec 07] Access Specifiers

Exampleclass Student{private:char * name;int rollNo;

public:void setName(char *);void setRollNo(int);

...};

Cannot be accessed outside class

Can be accessed outside class

Page 6: [OOP - Lec 07] Access Specifiers

Exampleclass Student{...int rollNo;

public:void setRollNo(int aNo);

};int main(){Student aStudent;aStudent.SetRollNo(1);

}

Page 7: [OOP - Lec 07] Access Specifiers

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;

};

Page 8: [OOP - Lec 07] Access Specifiers

Exampleclass Student{char * name;int RollNo;void SetName(char *);

};Student aStudent;aStudent.SetName(Ali);

Error

Page 9: [OOP - Lec 07] Access Specifiers

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