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

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Spring Semester 2013 Lecture 5
Structure.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Classes and Objects Presented by: Gunjan Chhabra.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Abstract Data Types Using Classes Lecture-5. Abstract Data Types Using Classes Representing abstract data types using C++ We need the following C++ keywords.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Object Oriented Programming (OOPs) Class Object Data Hiding Abstraction Encapsulation Polymorphism Inheritance Difference between Procedural and OOPs programming.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Chapter 6: User-Defined Functions
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Learners Support Publications Classes and Objects.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Learners Support Publications Functions in C++
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 CS161 Introduction to Computer Science Topic #9.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Chapter 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Course Title Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 07 classes 1 BY ADEEL ANJUM ( MSc - cs, CCNA, WEB DEVELOPER )
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Introduction to Object Oriented Programming (OOP) Object Oriented programming is method of programming.
Classes, Interfaces and Packages
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
ECE 103 Engineering Programming Chapter 31 C Scopes Herbert G. Mayer, PSU CS Status 8/1/2015 Initial content copied verbatim from ECE 103 material developed.
Classes Classes are a major feature of C++. They support – – Abstraction – Data hiding – Encapsulation – Modularity – Re-use through inheritance.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
Class & Objects C++ offers another user-defined data type known class which is the most important feature of the object-oriented programming. A class can.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Introduction to Classes and Objects CS-2303, C-Term C++ Program Structure Typical C++ Programs consist of:– main –A function main –One or more classes.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Object-Oriented Programming Using C++ Third Edition Chapter 7 Using Classes.
Lecture 3 (UNIT -1) SUNIL KUMAR CIT-UPES.
Structures and Classes
2 Chapter Classes & Objects.
Class and Objects UNIT II.
Chapter 5 Functions DDC 2133 Programming II.
This technique is Called “Divide and Conquer”.
Object-Oriented Programming Using C++
Lecture 4-7 Classes and Objects
Learning Objectives Classes Constructors Principles of OOP
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Chapter 9: Value-Returning Functions
Submitted By : Veenu Saini Lecturer (IT)
Classes and Objects Systems Programming.
Scope Rules.
Presentation transcript:

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.

The Class A 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.

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 };

Declaring a class The example of a class declaration is- Class item { private: int number ; // data members or class members float 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. };

Creating objects item X ; // memory for X is created 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.

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.

Defining member functions Member functions can be defined in two places – Outside the class definition (Using Scope Resolution Operator ::) 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; }

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”; }

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 starts void main ( ) { Item X; // create object X cout<<"object X"<<"\n"; X.getdata(100,98.3); // member function called X.putdata (); Item Y ; //creates another object Y cout <<"object Y"<<"\n"; Y.getdata (200,103.7); Y.putdata(); getch(); }

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.

Access limits of Class members No Yes Protected Private Public Object Subclass Class Access Permission Access Specifier

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(); }

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

Types of Member Function of a Class 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 Mutator / Setter – These functions allow us to change the data members of an object. 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.

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’ } };

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 ( ).

Functions in a Class 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); }

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.

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 –. A copy of the entire object is passed to the function. // by value. Only the address of the object is transferred to the function. // by reference.

Static Class Members 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; Static Member Function - A member function that accesses only the static members of a class may be declared as static . 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.

Static Class Members V/s Ordinary Class Members A static data member is different from ordinary data member of a class as- There is only one copy of static data member maintained for the entire class which is shared by all the objects of that class. It is visible only within the class, however, its life time is the entire program. 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.

Assignments 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. How does a class accomplish data abstraction and encapsulation ? What is the significance of scope resolution operator :: ? How are data and function organized in Object Oriented Programming ? When will you make a function inline and why ?

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; };

Define a class TEST in C++ with following description: Private Members TestCode 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 Members A 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

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;;

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)