Docsity

Object-Oriented Programming: Understanding Classes and Member Access, Slides of Object Oriented Programming

Partial preview of the text

Download Object-Oriented Programming: Understanding Classes and Member Access and more Slides Object Oriented Programming in PDF only on Docsity!

Object oriented programming

(OOP)

Lecture No. 7

Class

►

Class is a tool to realize objects

►

Class is a tool for defining a new type

Uses

►

The problem becomes easy to understand

►

Interactions can be easily modeled

Type in C++

►

Mechanism for user defined types are^ 

Structures  Classes

►

Built-in types are like int, float and double

►

User defined type can be^ 

Student in student management system  Circle in a drawing software

Defining a New User Defined Type

class

ClassName

… DataType

MemberVariable;

ReturnType

MemberFunction();

Syntax

Syntax

Example

class

Student

{

int

rollNo;

char

*name;

float

CGPA;

char

*address;

…

void

setName(char

*newName);

void

setRollNo(int

newRollNo);

… };

Member variables

Member Functions

Example

Student aStudent;aStudent.rollNo = 514;aStudent.rollNo = -514;

//Error

Object and Class

►

Object is an instantiation of a user definedtype or a class

Accessing members

►

Members of an object can be accessedusing^ 

dot operator (.) to access via the variable name  arrow operator (->) to access via a pointer toan object

►

Member variables and member functionsare accessed in a similar fashion

Example

class Student{

int rollNo;void setRollNo(intaNo); };

Student aStudent;aStudent.rollNo;

Error

Access specifiers

►

There are three access specifiers^ 

‘public’ is used to tell that member can beaccessed whenever you have access to theobject  ‘private’ is used to tell that member can only beaccessed from a member function  ‘protected’ to be discussed when we coverinheritance

Example

class Student{private:

char * name;int rollNo; public:

void setName(char *);void setRollNo(int); ...};

Cannot be accessed outside class

Can beaccessedoutside class

Default access specifiers

►

When no access specifier is mentioned thenby default the member is considered privatemember

Example

class Student{

char * name;int RollNo; };

class Student{ private:

char * name;int RollNo; };