CLASSES AND OBJECTS INTRODUCTION C class mechanism allows

CLASSES AND OBJECTS

INTRODUCTION C++ class mechanism allows users to define their own data types that can be used as conveniently as build in types. • Classes are often called user defined types. • Includes defining of class types and creation of objects of classes.

WHAT IS A CLASS? Created using keyword class. • A class declaration defines a new user defined data type that links code and data. • The new data type is then used to declare objects of that class. • Class is a logical abstraction but an object has physical existence. • Objects is an instance of class.

SYNTAX OF CLASS DECLARATION . CLASS NAME . { . //BODY OF A CLASS . }

GENERAL FORM OF CLASS DECLARATION . CLASS NAME . { . ACCESS_SPECIFIER_1: . MEMBERS; …… . } . OBJECT NAME;

Access specifier . PUBLIC . PRIVATE . PROTECTED

PUBLIC Public members may be accessed by member functions of same class and functions outside the scope of the class (anywhere inside the program)

PRIVATE Private members may only be accessed by member functions and friend function of the class. • A class that enforces information hiding declares its data members as private.

PROTECTED The protected members may be accessed only by the member functions of its class or by member functions of its derived class.

EXAMPLE CLASS TEXT { PRIVATE: INT A; INT B; PUBLIC: VOID SET DATA(INT X, INT Y) } A=X; B=Y; } INT BIG() { IF (A>B) RETURN A; ELSE RETURN B; } };

MEMBER FUNCTION � Member function’s name is visible outside the class. � It can be defined inside or outside the class. � It can have access to private, public and protected data members of its class, but cannot access private data members of another class.

INTRODUCTION TO OBJECTS � Object is an abstraction of real wold entity. � Objects are the variables/instances of classes. � Syntax for declaring objects is as follows : <class name> <obj_name 1>, <obj_name 2>, …, <obj_name 1> ; Example: for class test the objects can be created as follows: test t 1, t 2, …tn;

Characteristics of objects � It can have its own copy of data members. � The scope of an object is determined by the place in which the object is defined. � It can be passed to a function like normal variables. � The members of the class can accessed by the object using the object to member access operator or dot operator(. ).

EXAMPLE CLASS TEST { PRIVATE: INT A; INT B; PUBLIC; VOID SET_DATA(INT X, INT Y) { A=X; B=Y; } INT BIG() { IF(A>B) RETURN A; ELSE RETURN B; } }; VOID MAIN() { TEST T; INT A, B; COUT<<“ENTER THE TWO NUMBERS”<<ENDL; CIN>>A>>B; T. SET_DATA(A, B); COUT<<“THE LARGEST NUMBER IS”<<T. BIG()<<ENDL; }

- Slides: 15