 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 1 6.1 Introduction Object-oriented programming (OOP) –Objects Encapsulates.

Slides:



Advertisements
Similar presentations
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6: Classes and Data Abstraction Outline 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction 16.2Implementing a Time Abstract Data.
Introduction to Classes and Data Abstraction
1 Review (Week2) - Control Structures C++ has only seven control structures: –Sequence structure Programs executed sequentially by default –Selection structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
 2003 Prentice Hall, Inc. All rights reserved Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior)
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Classi - Esempi1 // SalesPerson class definition // Member functions defined in salesp.cpp #ifndef SALESP_H #define SALESP_H class SalesPerson { public:
1 Classes and Data Abstraction Andrew Davison Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University.
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Chapter 16 Classes and Data Abstraction Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
C++ Lecture 4 Tuesday, 15 July Struct & Classes l Structure in C++ l Classes and data abstraction l Class scope l Constructors and destructors l.
Chapter 10 Introduction to Classes
1 Chapter 4 CLASSES AND OBJECTS. 2 Outlines Procedural vs. Object ‑ Oriented Programming C++ Structures versus C Structures Classes –Accessing Class Members.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
1 Classes and Data Abstraction Part I Introduction Object-oriented programming (OOP)  Encapsulates data (attributes) and functions (behavior)
1 Classes and Data Abstraction 2 Objectives Understand encapsulation and data hiding Understand data abstraction and Abstract Data Types (ADTs) Create.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 6: Classes and Data Abstraction Outline 6.1Introduction 6.2Structure Definitions 6.3Accessing.
CLASSES : A DEEPER LOOK Chapter 9 Part I 1. 2 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition.
Chapter 9 Classes: A Deeper Look, Part I Part II.
Class 3 (L33) u Client of a Class u Purpose of Public Members u Private Class Members u Controlling Access u Access Functions u Predicate Functions u Utility.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
1 const and this Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24,
Class 4 (L34) u Constructors u Default Constructor u Example of Default Constructors u Destructors u Constructors Are Called in Global Scope u Constructors.
Classes and Data Abstraction Andrew Davison Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University 1
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 4: Classes Jan 27,
1 Lecture 6 Classes and Data Abstraction: Part II.
1 CMSC 202 ADTs and C++ Classes. 2 Announcements Project 1 due Sunday February 25 th at midnight – don’t be late! Notes and clarifications for Project.
EEL 3801 Part VI Fundamentals of C and C++ Programming Classes and Objects.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 6: Classes and Data Abstraction Posted Feb 3 Chapter 6 pointer for function Class Introduction.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 20 November 10, 2009.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7: Classes Part II Outline 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Review slides Mar 15, 2005.
Chapter 9 Classes: A Deeper Look, Part 1 Seventh Edition C++ How to Program © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. ECE 2552 Dr. Këpuska Summer 2004 from Dr. S. Kozaitis Spring 2003 slides 1 Summary of Chapter 6: Classes.
1 Example Original Array Array After 2 nd Pass Array After 1 st Pass Array After 3 rd Pass.
Chapter 16: Classes and Data Abstraction
Lecture 5: Classes (continued) Feb 1, 2005
Classes and Data Abstraction
Chapter 16: Classes and Data Abstraction
Classes: A Deeper Look Outline
Lecture 5: Classes September 14, 2004
Chapter 6: Classes and Data Abstraction
Chapter 9 Classes: A Deeper Look, Part 1
Chapter 6: Classes and Data Abstraction
Object-oriented programming (OOP)
Chapter 6: Classes and Data Abstraction
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Classes: A Deeper Look, Part 1
Chapter 6: Classes and Data Abstraction
Chapter 6: Classes and Data Abstraction
More C++ Classes Systems Programming.
Presentation transcript:

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf Introduction Object-oriented programming (OOP) –Objects Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding –Implementation details are hidden within the classes themselves Classes –Classes are the standard unit of programming –A class is like a blueprint or template – reusable –Objects are instantiated (created) from a class –For example, a house is an instance of a “blueprint class”

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 2 Object Oriented Programming Concepts Polymorphism From Greek - meaning “many forms”, is the quality that allows one interface to be used for a general class of action Abstraction Hiding all details except those that need to be exposed Encapsulation Combining code and data, like in object. Inheritance Inherit properties from the parent class and can have its own properties.

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 3 Structure Definitions Structures –Aggregate data types built using elements of other types –Similar to an array, except that arrays can only have data of one type. Structures can have data of many different types struct Time { int hour; int minute; int second; }; –Members (variable names) of the same structure must have unique names –Two different structures may contain members of the same name –Each structure definition must end with a semicolon Structure tag Structure members

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf Structure Definitions Self-referential structure –Contains a member that is a pointer to the same structure type –Used for linked lists, queues, stacks and trees struct –Creates a new data type that is used to declare variables –Structure variables are declared like variables of other types –Example: Time timeObject; //single object of type Time Time timeArray[ 10 ]; // array of objects of type Time Time *timePtr; // pointer to an object of type Time Time &timeRef = timeObject; // Reference

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf Accessing Members of Structures Member access operators: –Dot operator (. ) for structures and objects –Arrow operator ( -> ) for pointers –Print member hour of timeObject : cout << timeObject.hour; OR Time *timePtr; timePtr = &timeObject; cout hour; –timePtr->hour is the same as ( *timePtr ).hour –Parentheses required: * has lower precedence than.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 6 2. Create a struct data type 1. Define the struct 1.1 Define prototypes for the functions 2. Create a struct data type 2.1 Set and print the time 1// Fig. 6.1: fig06_01.cpp 2// Create a structure, set its members, and print it. 3#include 4 5using std::cout; 6using std::endl; 7 8struct Time { // structure definition 9 int hour; // int minute; // int second; // }; 13 14void printMilitary( const Time & ); // prototype 15void printStandard( const Time & ); // prototype 16 17int main() 18{ 19 Time dinnerTime; // variable of new type Time // set members to valid values 22 dinnerTime.hour = 18; 23 dinnerTime.minute = 30; 24 dinnerTime.second = 0; cout << "Dinner will be held at "; 27 printMilitary( dinnerTime ); 28 cout << " military time,\nwhich is "; 29 printStandard( dinnerTime ); 30 cout << " standard time.\n"; 31 Creates the user-defined structure type Time with three integer members: hour, minute and second. Dinner will be held at 18:30 military time, which is 6:30:00 PM standard time.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Set the time to an invalid hour, then print it 3. Define the functions printMilitary and printStandard 32 // set members to invalid values 33 dinnerTime.hour = 29; 34 dinnerTime.minute = 73; cout << "\nTime with invalid values: "; 37 printMilitary( dinnerTime ); 38 cout << endl; 39 return 0; 40} 41 42// Print the time in military format 43void printMilitary( const Time &t ) 44{ 45 cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":" 46 << ( t.minute < 10 ? "0" : "" ) << t.minute; 47} 48 49// Print the time in standard format 50void printStandard( const Time &t ) 51{ 52 cout << ( ( t.hour == 0 || t.hour == 12 ) ? : t.hour % 12 ) 54 << ":" << ( t.minute < 10 ? "0" : "" ) << t.minute 55 << ":" << ( t.second < 10 ? "0" : "" ) << t.second 56 << ( t.hour < 12 ? " AM" : " PM" ); 57} Time with invalid values: 29:73

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 8 Program Output Dinner will be held at 18:30 military time, which is 6:30:00 PM standard time. Time with invalid values: 29:73

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 9 // ENTERING DATA INTO A STRUCTURE // No memory allocated when defining a data type struct userInfo { int userid; char name[40]; float cur_balance; bool credit_risk; }; // Allocate memory space for an array of // structures (at compile time). userInfo user[2]; user[0].userid = 100; strcpy (user[0].name, "John Smith"); user[0].cur_balance = F; user[0].credit_risk = true; user[1].userid = 101; strcpy (user[1].name, "Mary Adams"); user[1].cur_balance = F; user[1].credit_risk = false; Note: Semicolon required

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 10 //DISPLAYING DATA FROM A STRUCTURE for (int i=0; i < 2; i++) cout << "UserID " << user[i].userid << ": " << "Name: " << user[i].name << ‘\t’ << "balance: $" << user[i].cur_balance << ‘\t’ << "Credit Risk: “ << ((user[i].credit_risk) ? "Yes": "No") << endl;

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 11 Memory Allocation (New & Delete) So far we have only seen variables which were either local or global These allocations are either for the duration of a function or duration of the program Sometimes data must be allocated for a time period different from local / global C used function calls such as malloc() to allocate memory and free() to deallocate memory C++ provides operators new and delete to accomplish these functions

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 12 Allocating memory dynamically Allocate memory dynamically (at run time) int *i = new int; *i = 33; cout << "Value of integer i is " << *i << " at Address " << hex << i << endl; delete i; new allocates memory and returns the address where memory was allocated. The amount of memory allocated depends on the argument after new. delete (de-allocates) free the memory from a specific location. If you provide a wrong address, an attempt is made to free memory, starting from that location. Most of the time this will result in a crash. Allocates memory of size equal to int. “i” points to that memory location. A value of 33 is assigned to the memory location pointed to by “i”. Release memory allocated at location pointed by i.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 13 Accessing DATA OF A STRUCTURE USING A POINTER Allocate memory dynamically (at run time) userInfo *pUser = new userInfo[2]; or allocate memory statically (at compile) userInfo user[2]; Assign address of user to Pointer pUser pUser = user; OR pUser = &user[0]; //create an additional pointer to hold the starting location. userInfo *pSaveUser = pUser; pUser is a pointer to structure of type userInfo. Allocate memory of size equivalent to two userInfo structures and point pUser to it. (Allocate memory for an array of 2 structures of type userInfo and point pUser to it.)

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 14 // Access each element of the structure and assign an // appropriate value. // Note: structure name is not used, pointer is used pUser->userid = 200; strcpy (pUser->name, "Mark Chen"); pUser->cur_balance = F; pUser->credit_risk = true; //Move to the next element of the array of structure. ++pUser; pUser->userid = 201; strcpy (pUser->name, "Dave Jones"); pUser->cur_balance = F; pUser->credit_risk = false;

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 15 // Access each element of the structure and assign an // appropriate value. // Note: structure name is not used, pointer is used //Go back to the beginning of the array of structures pUser = pSaveUser; //display the content of the structure for (i=0; i < 2; i++, pUser++) cout userid << ": “ name << ‘\t’ cur_balance <<‘\t’ << "Credit Risk: " credit_risk) ? "Yes": "No") << endl; // must point to the proper address before freeing memory. pUser = pSaveUser; delete [] pUser; Or delete [] pSaveUser; Or delete [] user; Free memory. This is because we allocated memory for an array.

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 16 Definition of Class Class is a user defined type and the basis for C++ It is very similar to a structure (of C++) It contains data and functions that operate on data It explicitly states what data and operations are hidden and which ones are exposed It contains the ability to initialize itself and clean up when it ceases to exist It’s properties and methods can be inherited It provides a secure interface

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 17 A Simple Class Declaration class myInt { public: // label, “member access specifiers” myInt() // Constructor ~ myInt(); // Destructor int m_Range; // public data private: // label, “member access specifiers” void Sum(void); // a private function int i; // private data double x, y; // private data };

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 18 Contents of a Class Constructor –Special member function that initializes the data members of a class object –Called whenever an object is made from a class – It has the same name as the class –Can take arguments and can be overloaded –Cannot return values Destructors –A function that is called when the object destructs (goes out of scope) –Has the same name as the class but preceded with a tilde character ( ~ ) –Cannot take arguments and cannot be overloaded –Performs “termination housekeeping”

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 19 Contents of a Class Properties or Data members –Built-in data type or user defined data type –Can be public or private Methods or member functions –Functions used to manipulate data members (get, set, modify) –Can be public, private or protected Format for defining member functions ClassName::MemberFunctionName( ) { … } Binary scope resolution operator (::) –Combines the class name with the member function name –Different classes can have member functions with the same name void ClassA::Swap( ){…} void ClassB::Swap( ){…}

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 20 Contents of a Class If a member function is defined inside the class –Scope resolution operator and class name are not needed –Defining a function outside a class requires the use of scope resolution operator and class name –Defining a function outside a class does not change it being public or private Classes encourage software reuse –Inheritance allows new classes to be derived from old ones

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 21 Contents of a Class Member access specifiers –Classes can limit the access to their member functions and data –The three types of access a class can grant are: Public — Accessible wherever the program has access to an object of the class private — Accessible only to member functions of the class Protected — Similar to private. We will not discuss this Size of object –Size of an object is really the size of it’s data –Each object has it’s own copy of the data –All the objects of a class share the methods

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 22 1class Time { 2public: 3 Time(); 4 void setTime( int, int, int ); 5 void printMilitary(); 6 void printStandard(); 7private: 8 int hour; // int minute; // int second; // }; Implementing a Time Abstract Data Type with a Class Classes –Objects that have attributes (data members) and behaviors (member functions) –Defined using keyword class –Have a body delineated with braces ( { and } ) –Class definitions terminate with a semicolon –Example: Public: and Private: are member-access specifiers. setTime, printMilitary, and printStandard are member functions. Time is the constructor. hour, minute, and second are data members.

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 23 Implementing a Time Abstract Data Type with a Class 1) class Time { 2) public: 3) Time(); 4) void setTime( int, int, int ); 5) void printMilitary(); 6) void printStandard(); 7) private: 8) int hour; // ) int minute; // ) int second; // ) }; Public: and Private: are member-access specifiers. setTime, printMilitary, and printStandard are member functions. Time is the constructor. hour, minute, and second are data members.

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 24 Implementing a Time Abstract Data Type with a Class Class definition and declaration –Once a class has been defined, it can be used as a type in object, array and pointer declarations –Example: Time sunset, // object of type Time arrayOfTimes[ 5 ], // array of Time objects *pointerToTime, // pointer to a Time object &dinnerTime = sunset; // reference to a Time object Note: The class name becomes the new type specifier.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 25 1// Fig. 6.3: fig06_03.cpp 2// Time class. 3#include 4 5using std::cout; 6using std::endl; 7 8// Time abstract data type (ADT) definition 9class Time { 10public: 11 Time(); // constructor 12 void setTime( int, int, int ); // set hour, minute, second 13 void printMilitary(); // print military time format 14 void printStandard(); // print standard time format 15private: 16 int hour; // 0 – int minute; // 0 – int second; // 0 – 59 19}; 20 21// Time constructor initializes each data member to zero. 22// Ensures all Time objects start in a consistent state. 23Time::Time() { hour = minute = second = 0; } 24 25// Set a new Time value using military time. Perform validity 26// checks on the data values. Set invalid values to zero. 27void Time::setTime( int h, int m, int s ) 28{ 29 hour = ( h >= 0 && h < 24 ) ? h : 0; 30 minute = ( m >= 0 && m < 60 ) ? m : 0; 31 second = ( s >= 0 && s < 60 ) ? s : 0; 32} Note the :: preceding the function names. 1. Define a Time class 1.1 Define default values for the time

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf // Print Time in military format 35void Time::printMilitary() 36{ 37 cout << ( hour < 10 ? "0" : "" ) << hour << ":" 38 << ( minute < 10 ? "0" : "" ) << minute; 39} 40 41// Print Time in standard format 42void Time::printStandard() 43{ 44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 45 << ":" << ( minute < 10 ? "0" : "" ) << minute 46 << ":" << ( second < 10 ? "0" : "" ) << second 47 << ( hour < 12 ? " AM" : " PM" ); 48} 49 50// Driver to test simple class Time 51int main() 52{ 53 Time t; // instantiate object t of class Time cout << "The initial military time is "; 56 t.printMilitary(); 57 cout << "\nThe initial standard time is "; 58 t.printStandard(); 59 Notice how functions are called using the dot (. ) operator. 1.2 Define the two functions printMilitary and printstandard 2. In main, create an object of class Time 2.1Print the initial (default) time The initial military time is 00:00 The initial standard time is 12:00:00 AM

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf t.setTime( 13, 27, 6 ); 61 cout << "\n\nMilitary time after setTime is "; 62 t.printMilitary(); 63 cout << "\nStandard time after setTime is "; 64 t.printStandard(); t.setTime( 99, 99, 99 ); // attempt invalid settings 67 cout << "\n\nAfter attempting invalid settings:" 68 << "\nMilitary time: "; 69 t.printMilitary(); 70 cout << "\nStandard time: "; 71 t.printStandard(); 72 cout << endl; 73 return 0; 74} The initial military time is 00:00 The initial standard time is 12:00:00 AM Military time after setTime is 13:27 Standard time after setTime is 1:27:06 PM After attempting invalid settings: Military time: 00:00 Standard time: 12:00:00 AM 2.2 Set and print the time 2.3 Set the time to an invalid hour 2.4 Print the time Program Output Military time after setTime is 13:27 Standard time after setTime is 1:27:06 PM After attempting invalid settings: Military time: 00:00 Standard time: 12:00:00 AM

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 28 Class Scope and Accessing Class Members Class scope –Data members and member functions File scope – Nonmember functions Inside a scope –Members accessible by all member functions Referenced by name Outside a scope –Members are referenced through handles An object name, a reference to an object or a pointer to an object

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 29 Class Scope and Accessing Class Members Function scope –Variables only known to function they are defined in –Variables are destroyed after function completion Accessing class members –Same as struct –Dot (. ) for objects and arrow ( -> ) for pointers –Example: t.hour is the hour element of t TimePtr->hour is the hour element

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Class definition 2. Create an object of the class 2.1 Assign a value to the object. Print the value using the dot operator 2.2 Set a new value and print it using a reference 1// Fig. 6.4: fig06_04.cpp 2// Demonstrating the class member access operators. and -> 3// 4// CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 5#include 6 7using std::cout; 8using std::endl; 9 10// Simple class Count 11class Count { 12public: 13 int x; 14 void print() { cout << x << endl; } 15}; 16 17int main() 18{ 19 Count counter, // create counter object 20 *counterPtr = &counter, // pointer to counter 21 &counterRef = counter; // reference to counter cout << "Assign 7 to x and print using the object's name: "; 24 counter.x = 7; // assign 7 to data member x 25 counter.print(); // call member function print cout << "Assign 8 to x and print using a reference: "; 28 counterRef.x = 8; // assign 8 to data member x 29 counterRef.print(); // call member function print 30 It is rare to have public member variables. Usually only member functions are public ; this keeps as much information hidden as possible.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Set a new value and print it using a pointer Program Output 31 cout << "Assign 10 to x and print using a pointer: "; 32 counterPtr->x = 10; // assign 10 to data member x 33 counterPtr->print(); // call member function print 34 return 0; 35} Assign 7 to x and print using the object's name: 7 Assign 8 to x and print using a reference: 8 Assign 10 to x and print using a pointer: 10

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 32 Separating Interface from Implementation Separating interface from implementation –Makes it easier to modify programs –Header files Contains class definitions and function prototypes –Source-code files Contains member function definitions

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 33 1// Fig. 6.5: time1.h 2// Declaration of the Time class. 3// Member functions are defined in time1.cpp 4 5// prevent multiple inclusions of header file 6#ifndef TIME1_H 7#define TIME1_H 8 9// Time abstract data type definition 10class Time { 11public: 12 Time(); // constructor 13 void setTime( int, int, int ); // set hour, minute, second 14 void printMilitary(); // print military time format 15 void printStandard(); // print standard time format 16private: 17 int hour; // int minute; // int second; // }; 21 22#endif If time1.h ( TIME1_H ) is not defined ( #ifndef ) then it is loaded ( #define TIME1_H ). If TIME1_H is already defined, then everything up to #endif is ignored. This prevents loading a header file multiple times. 1. Using the same Time class as before, create a header file Dot (. ) replaced with underscore ( _ ) in file name.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Create a source code file 2.1 Load the header file to get the class definitions 2.2. Define the member functions of the class 23// Fig. 6.5: time1.cpp 24// Member function definitions for Time class. 25#include 26 27using std::cout; 28 29#include "time1.h" 30 31// Time constructor initializes each data member to zero. 32// Ensures all Time objects start in a consistent state. 33Time::Time() { hour = minute = second = 0; } 34 35// Set a new Time value using military time. Perform validity 36// checks on the data values. Set invalid values to zero. 37void Time::setTime( int h, int m, int s ) 38{ 39 hour = ( h >= 0 && h < 24 ) ? h : 0; 40 minute = ( m >= 0 && m < 60 ) ? m : 0; 41 second = ( s >= 0 && s < 60 ) ? s : 0; 42} 43 44// Print Time in military format 45void Time::printMilitary() 46{ 47 cout << ( hour < 10 ? "0" : "" ) << hour << ":" 48 << ( minute < 10 ? "0" : "" ) << minute; 49} 50 51// Print time in standard format 52void Time::printStandard() 53{ 54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 55 << ":" << ( minute < 10 ? "0" : "" ) << minute 56 << ":" << ( second < 10 ? "0" : "" ) << second 57 << ( hour < 12 ? " AM" : " PM" ); 58} Source file uses #include to load the header file Source file contains function definitions

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 35 Controlling Access to Members public –Presents clients with a view of the services the class provides (interface) –Data and member functions are accessible private –Default access mode –Data only accessible to member functions and friend s –private members only accessible through the public class interface using public member functions

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 36 1// Fig. 6.6: fig06_06.cpp 2// Demonstrate errors resulting from attempts 3// to access private class members. 4#include 5 6using std::cout; 7 8#include "time1.h" 9 10int main() 11{ 12 Time t; // Error: 'Time::hour' is not accessible 15 t.hour = 7; // Error: 'Time::minute' is not accessible 18 cout << "minute = " << t.minute; return 0; 21} Compiling... Fig06_06.cpp D:\Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private member declared in class 'Time' D:\Fig6_06\time1.h(18) : see declaration of 'hour' D:\Fig06_06.cpp(18) : error C2248: 'minute' : cannot access private member declared in class 'Time' D:\time1.h(19) : see declaration of 'minute' Error executing cl.exe. test.exe - 2 error(s), 0 warning(s) Attempt to access private member variable minute. 1. Load header file for Time class 2. Create an object of class Time 2.1 Attempt to set a private variable 2.2 Attempt to access a private variable Program Output Attempt to modify private member variable hour.

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 37 Access Functions and Utility Functions Member functions –Read and return value of private data member ( Get ) –Set value of private data member ( Set ) –Initialize the object and it’s private data member ( constructor ) – Memory cleanup, un-initialize variables ( destructor ) –Utility functions. Called by other functions. private functions that support the operation of public functions Not intended to be used directly by clients –Access functions public functions that read/display data or check conditions Allow public functions to check private data Following example –Program to take in monthly sales and output the total –Implementation not shown, only access functions

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 38 87// Fig. 6.7: fig06_07.cpp 88// Demonstrating a utility function 89// Compile with salesp.cpp 90#include "salesp.h" 91 92int main() 93{ 94 SalesPerson s; // create SalesPerson object s s.getSalesFromUser(); // note simple sequential code 97 s.printAnnualSales(); // no control structures in main 98 return 0; 99} OUTPUT Enter sales amount for month 1: Enter sales amount for month 2: Enter sales amount for month 3: Enter sales amount for month 4: Enter sales amount for month 5: Enter sales amount for month 6: Enter sales amount for month 7: Enter sales amount for month 8: Enter sales amount for month 9: Enter sales amount for month 10: Enter sales amount for month 11: Enter sales amount for month 12: The total annual sales are: $ Create object s, an instance of class SalesPerson 1. Load header file and compile with the file that contains the function definitions 2. Create an object 2.1 Use the object’s member functions to get and print sales Program Output Use access functions to gather and print data ( getSalesFromUser and printAnnualSales ). Utility functions actually calculate the total sales, but the user is not aware of these function calls. Notice how simple main() is – there are no control structures, only function calls. This hides the implementation of the program.

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 39 Initializing Class Objects: Constructors Constructors –Initialize class members –Same name as the class –No return type –Member variables can be initialized by the constructor or set afterwards Passing arguments to a constructor –When an object of a class is declared, initializers can be provided –Format of declaration with initializers: Class-type ObjectName( value1,value2,…); –Default arguments may also be specified in the constructor prototype

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 40 1// Fig. 6.8: time2.h 2// Declaration of the Time class. 3// Member functions are defined in time2.cpp 4 5// preprocessor directives that 6// prevent multiple inclusions of header file 7#ifndef TIME2_H 8#define TIME2_H 9 10// Time abstract data type definition 11class Time { 12public: 13 Time( int = 0, int = 0, int = 0 ); // default constructor 14 void setTime( int, int, int ); // set hour, minute, second 15 void printMilitary(); // print military time format 16 void printStandard(); // print standard time format 17private: 18 int hour; // int minute; // int second; // }; 22 23#endif Notice that default settings for the three member variables are set in constructor prototype. No names are needed; the defaults are applied in the order the member variables are declared. 1. Define class Time and its default values

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 41 61// Fig. 6.8: fig06_08.cpp 62// Demonstrating a default constructor 63// function for class Time. 64#include 65 66using std::cout; 67using std::endl; 68 69#include "time2.h" 70 71int main() 72{ 73 Time t1, // all arguments defaulted 74 t2(2), // minute and second defaulted 75 t3(21, 34), // second defaulted 76 t4(12, 25, 42), // all values specified 77 t5(27, 74, 99); // all bad values specified cout << "Constructed with:\n" 80 << "all arguments defaulted:\n "; 81 t1.printMilitary(); 82 cout << "\n "; 83 t1.printStandard(); cout << "\nhour specified; minute and second defaulted:" 86 << "\n "; 87 t2.printMilitary(); 88 cout << "\n "; 89 t2.printStandard(); cout << "\nhour and minute specified; second defaulted:" 92 << "\n "; 93 t3.printMilitary(); 2. Create objects using default arguments 2.1 Print the objects Notice how objects are initialized: Constructor ObjectName ( value1,value2… ); If not enough values are specified, the rightmost values are set to their defaults.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf (continued) Print the objects. Program Output OUTPUT Constructed with: all arguments defaulted: 00:00 12:00:00 AM hour specified; minute and second defaulted: 02:00 2:00:00 AM hour and minute specified; second defaulted: 21:34 9:34:00 PM hour, minute, and second specified: 12:25 12:25:42 PM all invalid values specified: 00:00 12:00:00 AM When only hour is specified, minute and second are set to their default values of cout << "\n "; 95 t3.printStandard(); cout << "\nhour, minute, and second specified:" 98 << "\n "; 99 t4.printMilitary(); 100 cout << "\n "; 101 t4.printStandard(); cout << "\nall invalid values specified:" 104 << "\n "; 105 t5.printMilitary(); 106 cout << "\n "; 107 t5.printStandard(); 108 cout << endl; return 0; 111}

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 43 Using Destructors Destructors –Are member function of class –Perform termination housekeeping before the system reclaims the object’s memory –Complement of the constructor –Name is tilde ( ~ ) followed by the class name (i.e., ~Time ) Recall that the constructor’s name is the class name –Receives no parameters, returns no value –One destructor per class No overloading allowed

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 44 When Constructors and Destructors Are Called Constructors and destructors called automatically –Order depends on scope of objects Global scope objects –Constructors called before any other function (including main ) –Destructors called when main terminates (or exit function called) –Destructors not called if program terminates with abort Automatic local objects –Constructors called when objects are defined –Destructors called when objects leave scope i.e., when the block in which they are defined is exited –Destructors not called if the program ends with exit or abort

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 45 When Constructors and Destructors Are Called Static local objects –Constructors called when execution reaches the point where the objects are defined –Destructors called when main terminates or the exit function is called –Destructors not called if the program ends with abort

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 46 1// Fig. 6.9: create.h 2// Definition of class CreateAndDestroy. 3// Member functions defined in create.cpp. 4#ifndef CREATE_H 5#define CREATE_H 6 7class CreateAndDestroy { 8public: 9 CreateAndDestroy( int ); // constructor 10 ~CreateAndDestroy(); // destructor 11private: 12 int data; 13}; 14 15#endif 1. Create a header file 1.1 Include function prototypes for the destructor and constructor

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 47 16// Fig. 6.9: create.cpp 17// Member function definitions for class CreateAndDestroy 18#include 19 20using std::cout; 21using std::endl; 22 23#include "create.h" 24 25CreateAndDestroy::CreateAndDestroy( int value ) 26{ 27 data = value; 28 cout << "Object " << data << " constructor"; 29} 30 31CreateAndDestroy::~CreateAndDestroy() 32 { cout << "Object " << data << " destructor " << endl; } Constructor and Destructor changed to print when they are called. 2. Load the header file 2.1 Modify the constructor and destructor

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Create multiple objects of varying types 33// Fig. 6.9: fig06_09.cpp 34// Demonstrating the order in which constructors and 35// destructors are called. 36#include 37 38using std::cout; 39using std::endl; 40 41#include "create.h" 42 43void create( void ); // prototype 44 45CreateAndDestroy first( 1 ); // global object 46 47int main() 48{ 49 cout << " (global created before main)" << endl; CreateAndDestroy second( 2 ); // local object 52 cout << " (local automatic in main)" << endl; static CreateAndDestroy third( 3 ); // local object 55 cout << " (local static in main)" << endl; create(); // call function to create objects CreateAndDestroy fourth( 4 ); // local object 60 cout << " (local automatic in main)" << endl; 61 return 0; 62}

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf // Function to create objects 65void create( void ) 66{ 67 CreateAndDestroy fifth( 5 ); 68 cout << " (local automatic in create)" << endl; static CreateAndDestroy sixth( 6 ); 71 cout << " (local static in create)" << endl; CreateAndDestroy seventh( 7 ); 74 cout << " (local automatic in create)" << endl; 75} OUTPUT Object 1 constructor (global created before main) Object 2 constructor (local automatic in main) Object 3 constructor (local static in main) Object 5 constructor (local automatic in create) Object 6 constructor (local static in create) Object 7 constructor (local automatic in create) Object 7 destructor Object 5 destructor Object 4 constructor (local automatic in main) Object 4 destructor Object 2 destructor Object 6 destructor Object 3 destructor Object 1 destructor Notice how the order of the constructor and destructor call depends on the types of variables (automatic, global and static ) they are associated with. Program Output

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 50 Using Data Members and Member Functions Member functions –Allow clients of the class to set (i.e., write) or get (i.e., read) the values of private data members –Example: Adjusting a customer’s bank balance private data member balance of a class BankAccount could be modified through the use of member function computeInterest A member function that sets data member interestRate could be called setInterestRate, and a member function that returns the interestRate could be called getInterestRate –Providing set and get functions does not make private variables public –A set function should ensure that the new value is valid

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 51 A Subtle Trap: Returning a Reference to a Private Data Member Reference to an object –Alias for the name of the object –May be used on the left side of an assignment statement –Reference can receive a value, which changes the original object as well Returning references –public member functions can return non- const references to private data members Should be avoided, breaks encapsulation

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 52 1// Fig. 6.11: time4.h 2// Declaration of the Time class. 3// Member functions defined in time4.cpp 4 5// preprocessor directives that 6// prevent multiple inclusions of header file 7#ifndef TIME4_H 8#define TIME4_H 9 10class Time { 11public: 12 Time( int = 0, int = 0, int = 0 ); 13 void setTime( int, int, int ); 14 int getHour(); 15 int &badSetHour( int ); // DANGEROUS reference return 16private: 17 int hour; 18 int minute; 19 int second; 20}; 21 22#endif Notice how member function badSetHour returns a reference ( int & is the return type). 1. Define class 1.1 Function prototypes 1.2 Member variables

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Load header 1.1 Function definitions 23// Fig. 6.11: time4.cpp 24// Member function definitions for Time class. 25#include "time4.h" 26 27// Constructor function to initialize private data. 28// Calls member function setTime to set variables. 29// Default values are 0 (see class definition). 30Time::Time( int hr, int min, int sec ) 31 { setTime( hr, min, sec ); } 32 33// Set the values of hour, minute, and second. 34void Time::setTime( int h, int m, int s ) 35{ 36 hour = ( h >= 0 && h < 24 ) ? h : 0; 37 minute = ( m >= 0 && m < 60 ) ? m : 0; 38 second = ( s >= 0 && s < 60 ) ? s : 0; 39} 40 41// Get the hour value 42int Time::getHour() { return hour; } 43 44// POOR PROGRAMMING PRACTICE: 45// Returning a reference to a private data member. 46int &Time::badSetHour( int hh ) 47{ 48 hour = ( hh >= 0 && hh < 24 ) ? hh : 0; return hour; // DANGEROUS reference return 51} badSetHour returns a reference to the private member variable hour. Changing this reference will alter hour as well.

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf Declare reference 2. Change data using a reference 3. Output results 52// Fig. 6.11: fig06_11.cpp 53// Demonstrating a public member function that 54// returns a reference to a private data member. 55// Time class has been trimmed for this example. 56#include 57 58using std::cout; 59using std::endl; 60 61#include "time4.h" 62 63int main() 64{ 65 Time t; 66 int &hourRef = t.badSetHour( 20 ); cout << "Hour before modification: " << hourRef; 69 hourRef = 30; // modification with invalid value 70 cout << "\nHour after modification: " << t.getHour(); // Dangerous: Function call that returns 73 // a reference can be used as an lvalue! 74 t.badSetHour(12) = 74; 75 cout << "\n\n*********************************\n" 76 << "POOR PROGRAMMING PRACTICE!!!!!!!!\n" 77 << "badSetHour as an lvalue, Hour: " 78 << t.getHour() 79 << "\n*********************************" << endl; return 0; 82} Declare Time object t and reference hourRef that is assigned the reference returned by the call t.badSetHour(20). Alias used to set the value of hour to 30 (an invalid value). Function call used as an lvalue and assigned the value 74 (another invalid value). Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 *********************************

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 55 Program Output HourRef used to change hour to an invalid value. Normally, the function setbadSetHour would not have allowed this. However, because it returned a reference, hour was changed directly. Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 *********************************

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 56 Assignment by Default Memberwise Copy Assigning objects –An object can be assigned to another object of the same type using the assignment operator ( = ) –Member by member copy Objects may be –Passed as function arguments –Returned from functions (call-by-value default)

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf 57 1// Fig. 6.12: fig06_12.cpp 2// Demonstrating that class objects can be assigned 3// to each other using default memberwise copy 4#include 5 6using std::cout; 7using std::endl; 8 9// Simple Date class 10class Date { 11public: 12 Date( int = 1, int = 1, int = 1990 ); // default constructor 13 void print(); 14private: 15 int month; 16 int day; 17 int year; 18}; 19 20// Simple Date constructor with no range checking 21Date::Date( int m, int d, int y ) 22{ 23 month = m; 24 day = d; 25 year = y; 26} 27 28// Print the Date in the form mm-dd-yyyy 29void Date::print() 30 { cout << month << '-' << day << '-' << year; } 1. Define class 1.1 Define member functions

 2000 Prentice Hall, Inc. All rights reserved. Outline NHTI CP 107 Fall 2001 M. Saleem Yusuf int main() 33{ 34 Date date1( 7, 4, 1993 ), date2; // d2 defaults to 1/1/ cout << "date1 = "; 37 date1.print(); 38 cout << "\ndate2 = "; 39 date2.print(); date2 = date1; // assignment by default memberwise copy 42 cout << "\n\nAfter default memberwise copy, date2 = "; 43 date2.print(); 44 cout << endl; return 0; 47} date1 = date2 = After default memberwise copy, date2 = date2 set equal to date1, and all member variables are copied. 2. Create Date objects 2.1 Memberwise copy 3. Print values Program Output

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf Software Reusability Software resusability –Implementation of useful classes –Class libraries exist to promote reusability Allows for construction of programs from existing, well- defined, carefully tested, well-documented, portable, widely available components –Speeds development of powerful, high-quality software

 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf 60 MISC create a function that accepts run time arguments. Print out the arguments and the argument count. #include using namespace std;// use the std namespace. // C++ program entry with number of args and arg string. void main(int argc, char *argv[]) { for (int i=0; i<argc; i++) { cout << "arg" << i << ": "; //output to console arg num if (i == 0) // if this the first arg, it will print program name cout << "Program name is " << argv[i] << endl; else //for all other arguments, print this to console. cout << argv[i] << endl; } // end for-loop return ; }