classes & objects introduction : this chapter introduces classes ; explains data hiding,...

26
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these features. We will also discuss how to define a class, its public & private sections and how to create member functions that work with the class data.

Upload: abigail-gallegos

Post on 26-Mar-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Classes & Objects INTRODUCTION : This chapter introduces classes

; explains data hiding, abstraction & encapsulation and shows how a class implements these features.

We will also discuss how to define a class, its public & private sections and how to create member functions that work with the class data.

Page 2: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

The ClassA class is a way to bind the data & its associated functions together. It

allows the data & function to be hidden ,if necessary ,from external use. Generally a class specification has two parts :

1.Class Declaration – it describes the type & scope of its members.

2.Class function definition – it describes how the class function are implemented.

Page 3: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Declaring a class

The general form of a class declaration is-Class class_name

{private:

variable declaration; // data members or class members

function declaration;

public :variable declaration; // Member functions

function declaration;

};

Page 4: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Declaring a class

The example of a class declaration is-Class item

{private:

int number ; // data members or class membersfloat cost ; // are private by default

public :void getdata (int a, float b) ; // to assign values to the

//member variables number and

cost .

void putdata (void) ; // to display their values.

};

Page 5: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Creating objects

Once a class has been declared, we can create variables of that type by using the class name.

item X ; // memory for X is created It creates a variable of of type item. In c++ the class variables are known

as objects. Therefore X is called an object of type item. Objects can also be created when a class is defined by placing their names

immediately after the closing brace as we do in the case of structures. For e.g.-

class item

{ --------

------------ } x,y,z;

But usually we declare the objects close to the place where they are used & not at the time of class definition.

Page 6: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Accessing Class Members

Syntax – object_name.function_name (actual arguments);

Example – X.getdata (100,75.5)

here we assign the value 100 to number & 75.5 to cost of the object X by implementing the getdata( ). Similarly the statement X .putdata( ) would display the values of data members.

Page 7: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Defining member functions

Member functions can be defined in two places – 1. Outside the class definition (Using Scope Resolution Operator ::)

2. Inside the class definition When a member function is to be defined outside the class

definition, the following tasks are needed :- Declare the prototypes of the member function inside the class

definition. Bind the member function definition to a class to whom it belongs.

This is done using the scope resolution operator)

Syntax – return type Class name :: member function name (formal parameter list) { function body }

Example – void item :: get data (int a ,float b) { number = a; cost = b; }

Page 8: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Inside the class definition

When the member functions are defined inside the class definition , there is no need for function prototype declaration.

For e.g. void putdata (void)

{ cout << “number” <<number <<“\n”;cout <<“cost”<<cost <<“\n”;}

Page 9: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Program for class implementation#include <iostream.h>#include<conio.h>#include<string.h>class Item

{ int number;float cost;public: void getdata(int a , int b); // prototype declared

void putdata(void); // inside class definition{ cout<<"number:" <<number<<"\n"; cout<<"cost:"<<cost<<"\n"; } };

//member function declaration void Item :: getdata (int a,float b) // outside class defi. { number = a;

cost=b; // private variables directly used }// main program startsvoid main ( ){ Item X; // create object X

cout<<"object X"<<"\n";X.getdata(100,98.3); // member function calledX.putdata ();Item Y ; //creates another object Ycout <<"object Y"<<"\n";Y.getdata (200,103.7); Y.putdata(); getch(); }

Page 10: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Scope of Class & its Members

There are three access types that determine the scope of Class & its members – public , private and protected.

The public access specifier states that anything following this keyword can be accessed from outside this class .

The Private members are the class members that are hidden from the outside world. The private members implement the OOP concept of data hiding. The private members of a class can be used only member functions of the class in which it is declared.

The protected access specifier plays its role in inheritance i.e. when the new class is derived from the existing class. The protected members are similar to private members. The only difference between protected and private is that protected members are inheritable while private members are non-inheritable.

Page 11: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Access limits of Class members

NoYesYesProtected

NoNoYesPrivate

YesYesYesPublic

ObjectSubclassClass

Access PermissionAccess

Specifier

Page 12: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Program for access specifier (Public & Private)

#include<iostream.h>#include<conio.h>#include<stdio.h>Class customer{

private:char cust_name[25];char address[25];char city [15];double balance ;

public : void input_data(void){ cout<<“Enter the Name “;

gets (cust_name);cout<<“Enter Address”;gets(address);cout<<“Enter City”;gets(city);cout <<“Balance”;cin >>balance; }

void print_data (void) {cout<<“\n Customer Name “<<Cust_name;cout<<“\n Address”<<address;cout<<“\n City “<<city;cout<<“\n Balance”<< balance ; } };

void main( ) { customer cust; cust.input_data();cust.print_data(); }

Page 13: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Global V/s Local Class

Global Class– A Class is said to be global if its definition occurs outside the bodies of all functions in a program, which means that object of this class type can be declared from anywhere in the program.

for e.g. #include<iostream.h>

Class X // Global class type X

{…………..} ; X obj1; // Global object obj1 of type X

int main( )

{ X obj2; // Local object obj2 of type X

};

Local Class – A class is said to be local if its definition occurs inside a function body , which means that objects of this class type can be declared only within the function that defines this class type.

for Example - #include<iostream.h> -------------

int main ( ) { Class Y { ………… } // Local class type Y

Y obj1; }; // Local object obj 1 of type Y

Page 14: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Types of Member Function of a Class

1. Accessor /getter – are used to read values of private data members of a class which are directly not accessible in non-member function. However , accessor function do not change the value of data members

2. Mutator / Setter – These functions allow us to change the data members of an object.

3. Manager function – These are specific functions e.g. (Constructor and destructor) that deal with initializing and destroying class instances.

Why Accessor / Mutators –Because by providing accessor and mutator we make sure that data is edited in desired manner through a mutator .further if a user wants to know current value of a private data member , he can get it through an accessor function.

Page 15: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Program segment for Accessor & Mutator

Class student{ int rollno; char name[25]; float marks; char grade;public:

void read_data();void display_data():

int get rollno(){ return rollno; }

float get marks(){ return marks; } // accessor methods they have the return type.

void calgrade(){

if marks>= 75 // Mutator method it is modyfying data member grade

grade = ‘A’else if marks >= 60

grade= ‘B’else if marks >=45

grade = ‘C’}};

Page 16: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Arrays within a Class

A class can have an array as its member variable. An array in a class can be private or public data member of the class. If an array happens to be a private data member of the class, then, only the member functions of the class can access it. On the other hand, if an array is a public data member of the class, it can be accessed directly using objects of this class type.

For example - Class ABC { int arr [10]; // private by default

public :int largest (void);int sum (void);

};Here the variable arr[10] is a private data member of the class ABC. It can be

accessed only through the member function largest ( ) & sum ( ).

Page 17: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Functions in a Class

1. INLINE FUNCTION :- These functions are designed to speed up programs. The coding of these functions are like normal function except that inline function’s definitions start with the keyword “inline” . The other distinction between normal function and inline function is the different compilation process for them.

Inline functions run a little faster than the normal function. Inline function provide an alternative. With inline code the compiler replaces

the function call statement with the function code itself ( this process is called expansion) and then compiles the entire code.

Thus, with inline functions the compiler does not have to jump to another location to execute the function.

Declaration : inline void max (int a , int b)

{ cout << (a>b?a:b); } void main ( )

{ int x ,y ; cin >> x >> y; max (x , y); }

Page 18: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Tips for using inline function

In the above code the function max( ) has been declared inline, thus, it would not be called during execution. Rather its code would be inserted into main ( ) and then complied.

An inline function definition should be placed above all the functions that call it. The inline function does not work for following situations –

For functions that return values For functions having loop, switch or goto For have return ( ) If function contain static variables or is recursive.

The member function of a class ,if defined, within the class definition, are inlined by default. We need not use keyword inline.

Page 19: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Array of objects

An array having class type elements is known as Array of objects. An array of objects is declared after the class definition is over and it is defined in the same way as any other type of array is defined.

For example - class item { public:int itemno; float price;void getdata (int i, float j)};item order[10];

Here the array order contains 10 objects.To access data member itemno of 2nd object in the array we will give =

order[1].itemno; for more detail see program 4.4 of text book.

OBJECTS AS FUNCTION ARGUMENTS :An object may be used as a function argument in two ways –.

1. A copy of the entire object is passed to the function. // by value.2. Only the address of the object is transferred to the function. // by reference.

Page 20: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Static Class Members

1. Static Data Member - a static data member of a class is just like a global variable for its class. That is, this data member is globally available for all the objects of that class type. The static data members are usually maintained to store values common to the entire class.Declaration of static data member :

class X.{ static int count ; // within class.};int X :: count ; // for outside class.

A static data member can be given an initial value at the time of its definition like –int X :: count =10;

2. Static Member Function - A member function that accesses only the static members of a class may be declared as static . class X.

{ static int count ; // within class. static void show (void).

{ cout <<“count”; };};int X :: count ;

To call the static function show( ) of above defined class X we will give = X::show ( ); for more detail see program 4.8 of text book.

Page 21: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Static Class Members V/s Ordinary Class Members

1. A static data member is different from ordinary data member of a class as-1. There is only one copy of static data member maintained for the entire class which is

shared by all the objects of that class.2. It is visible only within the class, however, its life time is the entire program.

2. A static member function is different from ordinary member function of a class as-1. A static member function can access only static members of the same class.2. A static member fuction is invoked by using the class name instead of its

objects as -Class name :: function name X::show ( );

for more detail see program 4.8 of text book.

Page 22: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Assignments1. Define a class Book with the following specification :

Private members of the class Book are –Book_No integer ,Book_Title 20 char, Price float , (price per copy)

Total_Cost ( ) . A function to calculate the total cost for N numbers of copies, where N is passed to the function as argument.Public members of the class Book are –INPUT( ) function to read Book_No,Book_Title, Price.

PURCHASE() function to ask the user to input no. of copies to be purchased. It invokes Total_Cost( ) & prints the total cost to be paid by the user.

2. How does a class accomplish data abstraction and encapsulation ?

3. What is the significance of scope resolution operator :: ?

4. How are data and function organized in Object Oriented Programming ?

5. When will you make a function inline and why ?

Page 23: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Q.1 Solution

Class Book{ int BOOK_NO; char BOOK_TITLE[20]; float PRICE; float TOTAL_COST (int N)

{ float TOTAL ; TOTAL= N* PRICE;

return TOTAL; }public:

void INPUT() { cout<<“Enter Book No,:”; cin >>BOOK_NO.; cout <<“Enter Book Title:”; gets(BOOK_TITLE); cout <<“Enter Price:”; cin >> PRICE; } void PURCHASE() {

int a; float TOT; cout <<“Enter the no. of copies to be purchased:”; cin >>a; TOT= TOTAL_COST(a); cout <<“ Total Amount is :”<<TOT; }};

Page 24: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Define a class TEST in C++ with following description:

Private MembersTestCode of type integer

Description of type string

NoCandidate of type integer

CenterReqd (number of centers required) of type integer

A member function CALCNTR() to calculate and return the number of centers as (NoCandidates/100+1)

Public MembersA function SCHEDULE() to allow user to enter values for

TestCode, Description, NoCandidate & call function CALCNTR() to calculate the number of Centres

A function DISPTEST() to allow user to view the content of all the data members

Page 25: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

class TEST{

int TestCode;char Description[20];int NoCandidate,CenterReqd;void CALCNTR();

public:void SCHEDULE();void DISPTEST();

};void TEST::CALCNTR(){

CenterReqd=NoCandidate/100 + 1;}void TEST::SCHEDULE(){

cout<<”Test Code :”;cin>>TestCode;cout<<”Description :”;gets(Description);cout<<”Number :”;cin>>NoCandidate;CALCNTR();

}void TEST::DISPTEST(){

cout<<”Test Code :”<<TestCode<<endl;cout<<”Description :”<<Description<<endl;cout<<”Number :”<<NoCandidate<<endl;;cout<<”Centres :”<<CenterReqd<<endl;;

}

Page 26: Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these

Marking Scheme: (Total 4 marks)

(1 Mark for correctly declaring Data Members)

(1 Mark for correctly defining CALCNTR())

( ½ Mark for correctly defining SCHEDULE())

( ½ Mark for calling CALCNTR() from SCHEDULE())

( ½ Mark for correctly defining DISPTEST())

( ½ Mark for correct syntax of class)