Docsity

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

Partial preview of the text

Download Object-Oriented Programming: Understanding Classes and Access Specifiers 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 defined type or a class

Accessing members

  • Members of an object can be accessed using - dot operator (.) to access via the variable name - arrow operator (->) to access via a pointer to an object
  • Member variables and member functions are accessed in a similar fashion

Example

class Student{ int rollNo; void setRollNo(int aNo); };

Student aStudent; aStudent.rollNo;

Error

Access specifiers

  • 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

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

Default access specifiers

  • When no access specifier is mentioned then by default the member is considered private member

Example

class Student

{

char * name; int RollNo;

};

class Student { private: char * name; int RollNo; };