+ All Categories
Home > Documents > Classes and Objects Presented by: Gunjan Chhabra.

Classes and Objects Presented by: Gunjan Chhabra.

Date post: 18-Dec-2015
Category:
Upload: dorthy-bradley
View: 219 times
Download: 4 times
Share this document with a friend
Popular Tags:
41
Classes and Objects Presented by: Gunjan Chhabra
Transcript
Page 1: Classes and Objects Presented by: Gunjan Chhabra.

Classes and ObjectsPresented by:

Gunjan Chhabra

Page 2: Classes and Objects Presented by: Gunjan Chhabra.

Classes are most important feature of C++ Its initial name was “C with classes” Class is an extension idea of structure used in C A new way of creating and implementing user-

defined data type.

Introduction

Page 3: Classes and Objects Presented by: Gunjan Chhabra.

Provide method for packing together data of different types

Tool for handling group of logically related data items Example:

struct student{ char name[20];

int roll_num; three fields with diff. data types-

float total_marks; structure members or elements};

Structures Revised

Student- new data type

Page 4: Classes and Objects Presented by: Gunjan Chhabra.

Structure name (student) can be used to create variable of type student. Example:

struct student A; // C declaration Dot opertaor is used for accessing member variables as:

strcpy(A.name, “John”);A.roll_num =25;A.total_marks =550;final_result = A.total_marks + 20;

Structures can have array, pointers or structures as members.

Structures Revised

Page 5: Classes and Objects Presented by: Gunjan Chhabra.

Limitations of C structures: Struct data type can not be treated as built-in types, as shown:

struct sum{

float x;float y;

};struct sum a, b, c;

Values can easily be assigned to a, b, c using dot operator but we can not add or subtract one from other, as shown:

a= b+c; // illegal in C Secondly, no data hiding in structures i.e. structure members can be

directly accessed by other structure variables by any function anywhere in their scope. Means structure members are public members.

Structures Revised

Page 6: Classes and Objects Presented by: Gunjan Chhabra.

C++ supports all the features of structures in C but expanded its capabilities to suits OOP philosophy

User-defined data types to be treated as close as possible to the built-in data types

Feature of DATA HIDING (one of the main principles of OOP)

In C++, both variables and functions be used as members

Some members can be declared as private so that can not be accessed by others directly.

Keyword struct can be omitted in the declaration of structure variable, example:

student A; // legal in C++ but illegal in C

Extensions to Structure

Page 7: Classes and Objects Presented by: Gunjan Chhabra.

C++ includes all these extensions in another user-defined type called class.

Small syntactical difference b/w structures and classes in C++, hence one can use both interchangeably with minor modifications.

Most of the programmers use structures for holding data and classes for both data and functions.

The only difference between structure and class in C++ is that, by default, members of class is private while public in case of structure.

Extensions to Structure

Page 8: Classes and Objects Presented by: Gunjan Chhabra.

A way to bind data and functions together and allows data to be hidden, if required, from external use

While defining class, we are creating a new abstract data type that can be treated as any other built-in data type.

Two parts of class specification: Class declaration- describes the type and scope

of its members Class function definitions- describes how the

class functions are implemented.

Class

Page 9: Classes and Objects Presented by: Gunjan Chhabra.

General declaration of class:class class_name{

private:variable declarations;function declarations;public: Class membersvariable declarations;function declarations;

};

Class

Data hiding

Page 10: Classes and Objects Presented by: Gunjan Chhabra.

Variable declared inside class are- data members and function are- member functions.

Only member functions can have access to the private data members and private functions

Binding of data and functions together into a single class-type variable is referred to as encapsulation.

Class

Page 11: Classes and Objects Presented by: Gunjan Chhabra.

Simple example:class item{

int number; //variables declarationfloat cost; //private by default

public:void getdata(int a, float b); // function

declarationvoid putdata(void);};

Class

Page 12: Classes and Objects Presented by: Gunjan Chhabra.

Remember- class declaration does not define any object of class but only specifies what they contain

Once class is declared, we can create variable of that type by using the class name, say item z; // memory for z is created Here the class variables are known as objects, so z is object of type

item One can declare more than one object in one statement, say- item a,

b, c; Also possible way, like in structures, for creating objects is:

Class item{…….} a, b, c;

Object Creation

Page 13: Classes and Objects Presented by: Gunjan Chhabra.

The main() cannot contain statements that access data members directly. They can only be accessed through member functions.

Syntax for accessing class members- object-name.function-name(actual-arguments);Example: x.getdata(500, 42.5); // is valid for object zSimilarly- x.putdata(); //would display values

Accessing Class Members

Page 14: Classes and Objects Presented by: Gunjan Chhabra.

Invalid statements- getdata(100, 42.5); x.number= 300; //such statements have no meaning Variable declared as public can be accessed by objects directly, as shown:

class xyz{

int x;int y;

public:int z;

};………xyz p;p.x =10; //error, x is privatep.z =20 // accepted, z is public, should be avoided (defeats idea of data hiding)…........

Accessing Class Members

Page 15: Classes and Objects Presented by: Gunjan Chhabra.

Two places: Outside the class definition Inside the class definition

Irrespective of the place of function definition, the function should perform the same task.

Defining Member function

Page 16: Classes and Objects Presented by: Gunjan Chhabra.

Difference b/w member function and normal function is that a member function incorporates a membership ‘identical label’ in the header.

This ‘label’ tells the compiler which class the function belongs to.

Member function definition:return-type class-name :: function-name (argument declaration){Function body}

Outside the Class Definition

Page 17: Classes and Objects Presented by: Gunjan Chhabra.

:: scope resolution operator, tells the compiler that the function function-name belongs to the class class-name.

This means, scope of the function is restricted to the class-name specified in the header line.

For example:Void item :: getdata( int a, float b){Number = a;Cost = b;}Void item :: putdata(void){Cout<< “number :”<< number << “\n”;Cout<< “cost :”<< cost << “\n”;}

Outside the Class Definition

Page 18: Classes and Objects Presented by: Gunjan Chhabra.

Characteristics of member functions: Several different classes can use the same function

name. Member functions can access the private data of the

class. A member function can call another member

function directly, without using the dot operator.

Outside the Class Definition

Page 19: Classes and Objects Presented by: Gunjan Chhabra.

Example:class item {

int number;Float cost;Public:Void getdata(int a, float b);Void putdata(void) //treated as inline function{Cout << number << “\n”;Cout << cost << “\n”;}

};

Inside the Class Definition

Page 20: Classes and Objects Presented by: Gunjan Chhabra.

Function defined inside class is treated as inline function.

Hence all restrictions and limitations that apply to an inline function are also applicable here.

Only small functions are defined inside the class definition.

Inside the Class Definition

Page 21: Classes and Objects Presented by: Gunjan Chhabra.

# include <iostream.h>Class item{

Int number;Float cost;Public:Void getdata(int a, float b);Void putdata(void){Cout<<“number :” <<number<< “\n”;Cout<<“cost :” <<cost<< “\n”;}

};Void item :: getdata(int a, float b){Number=a;Cost=b;}

C++ with class

Page 22: Classes and Objects Presented by: Gunjan Chhabra.

int main (){

item x;cout<< “\nobject x” << “\n”;x.getdata (200, 140.55);x.putdata();item y;cout<< “\nobject y” << “\n”;y.getdata (700, 159.32);y.putdata();return 0;

} Use keyword inline to make function inline outside the class.

C++ with class

Page 23: Classes and Objects Presented by: Gunjan Chhabra.

When a member function can be called by using its name inside another member function of the same class, it is known as nesting of member function.Ex-# include<iostream.h>class set{int m, n;public:void input (void);void display (void);int largest(void);};int set:: largest (void){if (m >= n)return (m);elsereturn (n);}void set : : input (void){cout << “input values of m & n:”;

Nesting of member functions

Page 24: Classes and Objects Presented by: Gunjan Chhabra.

int set:: largest (void){if (m >= n)return (m);elsereturn (n);}void set : : input (void){cout << “input values of m & n:”;cin >> m >> n;}void set :: display(void){cout << “largest value = “ <<largest(); //calling member function}main(){set aa.input();a.display();}

Nesting of member functions

Page 25: Classes and Objects Presented by: Gunjan Chhabra.

Although we place all data items in a private section and all the functions in public, some situation may require certain function to be hidden from the outside calls.

We can place these functions in the private section. A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using the dot operator.

Private Member Functions

Page 26: Classes and Objects Presented by: Gunjan Chhabra.

Consider following class:class sample{int m;void read(void);public:void update(void);void write(void);};If s1 is an object of sample thens1.read(); // will not work , object cannot access private data.

// read() can be called by the function update() to update the value of m.void sample :: update (void){read(); // a simple call}

Private Member Functions

Page 27: Classes and Objects Presented by: Gunjan Chhabra.

The member functions are created & place in the memory space only once when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions no separate space is allocated for member functions when the objects are created only space for member variables is allocated separately for each object.

Memory allocation for Objects

Page 28: Classes and Objects Presented by: Gunjan Chhabra.

Memory allocation for Objects

Page 29: Classes and Objects Presented by: Gunjan Chhabra.

A data member of a class can be qualified as static. A static member variable has certain special characteristics these are: It is initialized to zero when the first object of its

class is crated. No other initialization is permitted. Only one copy of that member is created for the

entire class and is shared by all the objects of that class, no matter how many objects are created.

It is visible only within the class, but its lifetime is the entire program.

Static Data Members

Page 30: Classes and Objects Presented by: Gunjan Chhabra.

Static variables are normally used to maintain values common to the entire class for Ex - A static data member can be used as a counter that records the occurrences of all the objects.# include<iostream.h>class item{static int count;int number;public :void getdata(int a){number = a;count ++;}void get count (void){count << “count :”;count << count << “\n”;}};

Static Data Members

Page 31: Classes and Objects Presented by: Gunjan Chhabra.

int item : : count; //definition of static data memberint main ( ){item a, b, c;a.getcount() ;a.getcount() ;a.getcount() ;a.getdata(100);a.getdata(200);a.getdata(300);cout <<“After reading data”;a.getcount();b.getcount();c.getcount();return 0;}

Static Data Members

Page 32: Classes and Objects Presented by: Gunjan Chhabra.

the output would be: count : 0count : 0count : 0

After reading datacount : 3count : 3count : 3 Type and scope of the static member variable must be

defined outside the class definition because static data members are stored separately.

Static Data Members

Page 33: Classes and Objects Presented by: Gunjan Chhabra.

The count is incremented whenever the data is read into an object. Since the data is read into objects three times, variable count is incremented three times.

Static variables are like non inline member functions in that they are declared in a class declaration & defined in the source file.

Value initialization to static variables is also possible as shown: Int item :: count = 10;

Static Data Members

Page 34: Classes and Objects Presented by: Gunjan Chhabra.

A FRIEND is one who can access all your “PRIVATE” stuff.

Friend function is non-member function which has access to all the Protected and Private Members of class

Friend Function

Page 35: Classes and Objects Presented by: Gunjan Chhabra.

Normal function- A member is access through the object. Ex: sample obj; obj.getvalue();

Friend function- requires object to be passed by value or by reference by parameter.

Ex: void getdata(sample obj);

Friend Function

Page 36: Classes and Objects Presented by: Gunjan Chhabra.

class demo{int x;public:demo(int xx){x=xx;}friend void display(demo); //Declaration inside the class};void display(demo dd1) //Definition outside the class{cout<<dd1.x;}

Friend Function

Page 37: Classes and Objects Presented by: Gunjan Chhabra.

What are its Disadvantages? Violates Data Hiding Violates encapsulation

– Properties– Friendship is granted, not taken– NOT symmetric (if B a friend of A, A not necessarily

a friend of B) – NOT transitive (if A a friend of B, B a friend of C, A

not necessarily a friend of C)

Friend Function

Page 38: Classes and Objects Presented by: Gunjan Chhabra.

Provides the same feature as that of Friend Fn. Allows “member fn” of one class to friend of other

class i.e. the private member of the class will be accessible

to the friend class

Friend Class

Page 39: Classes and Objects Presented by: Gunjan Chhabra.

class xxx{ int x;public:xxx(int xx){ x=xx;}friend class yyy;};class yyy{public:void f1(xxx obj){ cout<<“x=”<<obj.x;}};

Friend Class

Page 40: Classes and Objects Presented by: Gunjan Chhabra.

#include <iostream.h>class ABC; //Forward declarationclass XYZ;{ int x;

public:void setvalue (int i) {x = i; }friend void max (XYZ, ABC);

};Class ABC;{ int a; public:void setvalue (int i) {x = i; }friend void max (XYZ, ABC);};

Friend function to two classes

Page 41: Classes and Objects Presented by: Gunjan Chhabra.

void max ( XYZ m, ABC n) //definition of friend{if (m.x >= n.a)cout <<m.x;else cout<< n.a;}int main (){ ABC abc;abc.setvalue(10);XYZ xyz;xyz.setvalue(20);max (xyz, abc);return 0; }

Friend function to two classes


Recommended