Chapter 14 More About Classes. CS 1410 - SJAllan Chapter 14 2 Instance and Static Members Instance variable:  A member variable in a class  Each object.

Slides:



Advertisements
Similar presentations
Starting Out with C++, 3 rd Edition 1 Chapter 14 – More About Classes.
Advertisements

Lesson 14 Classes, Continued CS1 Lesson More Classes1.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Operator Overloading Fundamentals
Class and Objects.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Chapter 14: Overloading and Templates
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 11 More.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 11: More About.
Starting Out with C++, 3 rd Edition 1 Chapter 14: more about classes Static Members If a member variable is declared static, all objects of that class.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
More About Classes. C++: Classes & Objects -2 2 Instance and Static Members Each instance of a class has its own copies of the class’s instance (member)
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Chapter 11: More About Classes and Object-Oriented Programming
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 CSC241: Object Oriented Programming Lecture No 22.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 14 More About Classes. Chapter 13 slide 2 Topics 13.1 Instance and Static Members 13.2 Friends of Classes 13.3 Memberwise Assignment 13.4 Copy.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
More C++ Features True object initialisation
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Review 1 List Data Structure List operations List Implementation Array Linked List.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
1 CS161 Introduction to Computer Science Topic #16.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 CSE 2341 Object Oriented Programming with C++ Note Set #7.
Starting Out with C++, 3 rd Edition 1 Chapter 14 – More About Classes.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Operator Overloading.
Yan Shi CS/SE 2630 Lecture Notes
Chapter 14: More About Classes.
Operator Overloading; String and Array Objects
CSC241: Object Oriented Programming
Overloading Operator MySting Example
14.4 Copy Constructors.
Pointers and Pointer-Based Strings
group work #hifiTeam
Chapter 14: More About Classes.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Operator Overloading; String and Array Objects
Operator Overloading; String and Array Objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
Object Oriented Programming Using C++
Pointers and Pointer-Based Strings
Chapter 18 - Operator Overloading
Chapter 14 – More About Classes
Presentation transcript:

Chapter 14 More About Classes

CS SJAllan Chapter 14 2 Instance and Static Members Instance variable:  A member variable in a class  Each object has its own copy static variable:  One variable shared among all objects of a class static member function:  Can be used to access static member variable  Can be called before any objects are defined

CS SJAllan Chapter 14 3 Member (Instance)Variables Object W1, W2

CS SJAllan Chapter 14 4 Member Variable is Static

CS SJAllan Chapter 14 5 Budget.h – Program #ifndef BUDGET_H #define BUDGET_H class Budget {private: static double corpBudget; double divBudget; public: Budget ( void ) { divBudget = 0; } void addBudget ( double b ) { divBudget += b; corpBudget += b; } double getDivBudget ( void ) { return divBudget; } double getCorpBudget ( void ) { return corpBudget; } }; // Budget double Budget::corpBudget = 0; // Static member #endif

CS SJAllan Chapter 14 6 testB udget.cpp – Program #include #include "Budget.h" using namespace std; int main ( void ) {int count; const int NUMDIVISIONS = 4; Budget divisions[NUMDIVISIONS]; for ( int count = 0; count < NUMDIVISIONS; count++ ) {double bud; cout << "Enter the budget request for division "; cout << (count + 1) << ": "; cin >> bud; divisions[count].addBudget(bud); } // for

CS SJAllan Chapter 14 7 testB udget.cpp – Program cout << fixed << showpoint < setprecision(2); cout << "\nHere are the division budget requests:\n"; for ( int count = 0; count < NUMDIVISIONS; count++ ) {cout << "\tDivision " << (count + 1) << "\t$ "; cout << divisions[count].getDivBudget() << endl; } // for cout << "\tTotal Budget Requests:\t$ "; cout << divisions[0].getCorpBudget() << endl; return 0; } // main

CS SJAllan Chapter 14 8 testBudget.cpp – Output Enter the budget request for Division 1: [Enter] Enter the budget request for Division 2: [Enter] Enter the budget request for Division 3: [Enter] Enter the budget request for Division 4: [Enter] Here are the division budget requests: Division 1$ Division 2$ Division 3$ Division 4$ Total Budget Requests:$

CS SJAllan Chapter 14 9 Static Member Functions Declared with static before return type: static int getVal ( ) { return valueCount; } Can only access static member data Can be called independent of objects: cout << "There are " << IntVal::getVal( ) << " objects\n " ;

CS SJAllan Chapter A New B udget.h – Program #ifndef BUDGET_H #define BUDGET_H class Budget {private: static double corpBudget; double divBudget; public: Budget ( void ) { divBudget = 0; } void addBudget ( double b ) { divBudget += b; corpBudget += b; } double getDivBudget ( void ) { return divBudget; } double getCorpBudget ( void ) { return corpBudget; } static void mainOffice ( double ); }; // Budget #endif

CS SJAllan Chapter Budget.cpp – Program #include "budget.h" double Budget::corpBudget = 0; void Budget::mainOffice ( double moffice ) {corpBudget += moffice; } // Budget::mainOffice

CS SJAllan Chapter testBudget.cpp – Program #include #include "Budget.h" using namespace std; int main ( void ) {int count; double mainOfficeRequest const int NUMDIVISIONS = 4; cout << "Enter the main office's budget request: "; cin >> mainOfficeRequest; Budget::mainOffice( mainOfficeRequest ); Budget divisions[NUMDIVISIONS]; for ( count = 0; count < NUMDIVISIONS; count++ ) {double budgetAmount; cout << "Enter the budget request for division "; cout << ( count + 1 ) << ": "; cin >> budgetAmount; divisions[count].addBudget( budgetAmount ); } // for

CS SJAllan Chapter testBudget.cpp – Program cout << fixed << showpoint << setprecision(2); cout << "\nHere are the division budget requests:\n"; for (int count = 0; count < NUMDIVISIONS; count++) {cout << "\tDivision " << ( count + 1 ) << "\t$ "; cout << divisions[count].getDivBudget() << endl; } // for cout << "\tTotal Budget Requests (including main office):\t$ "; cout << divisions[0].getCorpBudget( ) << endl; return 0; } // main

CS SJAllan Chapter testB udget.cpp – Output Enter the main office's budget request: [Enter] Enter the budget request for Division 1: [Enter] Enter the budget request for Division 2: [Enter] Enter the budget request for Division 3: [Enter] Enter the budget request for Division 4: [Enter] Here are the division budget requests: Division 1$ Division 2$ Division 3$ Division 3$ Total Requests (including main office): $

CS SJAllan Chapter Friends of Classes Friend  A function or class that is not a member of a class, but has access to private members of the class A friend function can be a stand-alone function or a member function of another class It is declared a friend of a class with friend keyword in the function prototype

CS SJAllan Chapter Friend Function Declarations Stand-alone function: friend void setAVal ( intVal &, int );  Declares setAVal function be a friend of this class Member function of another class: friend void SomeClass::setNum( int num );  setNum function from Someclass class is a friend of this class

CS SJAllan Chapter Friend Classes As mentioned before, it is possible to make an entire class a friend of another class. class FriendClass { … }; // FriendClass class NewClass {public: friend class FriendClass; // declares entire class (Friendclass) as a friend of this class … }; // NewClass

CS SJAllan Chapter Memberwise Assignment The assignment operator (=) may be used to assign one object to another, or to initialize one object with another object’s data Thus v2 = v1; means that each member of one object is copied to its counterpart in the other object Use when class is defined: IntVal v3 = v2;

CS SJAllan Chapter Copy Constructors A copy constructor is a special constructor, called whenever a new object is created and initialized with another object’s data Assume the class PersonInfo has a member variable as follows: name char *. Consider the following declarations:  PersonInfo person1( "Maria Jones-Tucker", 25 );  PersonInfo person2 = person1;

CS SJAllan Chapter PersonInfo person1("Maria Jones-Tucker", 25); Maria Jones-Tucker Dynamically allocated memory name p ointer

CS SJAllan Chapter PersonInfo person2 = person1; Maria Jones-Tucker Both objects’ name members point to the same section of memory person1’s name pointer person2’s name pointer Dynamically allocated memory

CS SJAllan Chapter Programmer Defined Copy Constructor Allows us to solve the problem with pointers PersonInfo::PersonInfo( PersonInfo &obj ) {name = new char[strlen( obj.name ) + 1]; strcpy( name, obj.name ); age = obj.age; } // PersonInfo::PersonInfo Copy constructor takes a reference parameter to an object of the class

CS SJAllan Chapter Programmer Defined Copy Constructor Consider the following: PersonInfo info1( " Ann ", 5 ); PersonInfo info2 = info1; info2.setName( " Jane " ); name info1 name info2 “Ann”“Jane”

CS SJAllan Chapter Using const Parameters Because copy constructors are required to use reference parameters, they have access to their argument’s data PersonInfo::PersonInfo( PersonInfo &obj ) They should not be allowed to change the parameters, therefore, it is a good idea to make the parameter const so it can’t be modified PersonInfo::PersonInfo( const PersonInfo &obj )

CS SJAllan Chapter The Default Copy Constructor If a class doesn’t have a copy constructor, C++ automatically creates a default copy constructor The default copy constructor performs a memberwise assignment

CS SJAllan Chapter Operator Overloading C++ allows you to redefine how standard operators work when used with class objects

CS SJAllan Chapter Overloading the = Operator This is done with a member function such as: void operator = ( const PersonInfo &right ); This member function is called as follows:  person2 = person1;  person2.operator = ( person1 );  Note that the parameter, right, is declared as a reference, for efficiency purposes The reference prevents the compiler form making a copy of the object being passed into the function Also note that the parameter is declared constant so the function does not accidentally change the contents of the argument

CS SJAllan Chapter Operator Overload – Program #include using namespace std; class PersonInfo {private: char *name; int age; public: PersonInfo ( char *n, int a ) { name = new char[strlen(n) + 1]; strcpy(name, n); age = a; } PersonInfo ( const PersonInfo &obj ) // Copy constructor { name = new char[strlen(obj.name) + 1]; strcpy(name, obj.name); age = obj.age; } ~PersonInfo ( void ) { delete [] name; } char *getName ( void ) { return name; } int getAge ( void ) { return age; } void operator= ( const PersonInfo &right ) { delete [] name; name = new char[strlen( right.name ) + 1]; strcpy(name, right.name); age = right.age; } }; // PersonInfo

CS SJAllan Chapter Operator Overload – Program int main ( void ) {PersonInfo jim("Jim Young", 27), bob("Bob Faraday", 32), clone = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; cout << "Now the clone will change to Bob and "; cout << "Bob will change to Jim.\n"; clone = bob; bob = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; return 0; } // main

CS SJAllan Chapter Operator Overload – Output The Jim Object contains: Jim Young, 27 The Bob Object contains: Bob Faraday, 32 The Clone Object contains: Jim Young, 27 Now the clone will change to Bob and Bob will change to Jim. The Jim Object contains: Jim Young, 27 The Bob Object contains: Jim Young, 27 The Clone Object contains: Bob Faraday, 32

CS SJAllan Chapter The = Operator’s Return Value If the operator= function returns a void, as in the previous example, then multiple assignment statements won’t work To enable a statement such as person3 = person2 = person1; you must have the following prototype: PersonInfo operator= (const PersonInfo &Right);

CS SJAllan Chapter The this Pointer this is a special built-in pointer that is available in any member function this contains the address of the object that called the member function The this pointer is passed as a hidden argument to all non-static member functions

Use of this pointer This refers to the class itself. CS SJAllan Chapter 14 33

You can use “this” to refer to class variables. Class MyInt { private: int a; public: void MyInt(int a) { // The 'this' pointer is used to get access to class variable “a” rather than local variable “a” this->a = a; } void doit(){ } }; CS SJAllan Chapter 14 34

You can use “this” even when it is the not required Class MyInt { private: int a; public: void MyInt(int a) { this->a = a; doit(); // both of these calls to the same thing. “this” is understood this->doit(); // both of these calls to the same thing. “this” is understood } void doit(){ cout << “just Called contructor”;} } }; CS SJAllan Chapter 14 35

Sometimes you need a name for yourself. “this” is that name Class MyInt { private: int a; public: void MyInt(int a) { this->a = a; } MyInt* returnBigger(MyInt * other){ if (other->a > a) return other; return this; // If I am the bigger, return me! } }; CS SJAllan Chapter 14 36

The this Pointer PersonInfo person1, person2; cout << person1.getName( ) << endl;  What does the this pointer point to? cout << person2.getName( ) << endl;  What does the this pointer point to? CS SJAllan Chapter 14 37

CS SJAllan Chapter Using this – Program #include using namespace std; class PersonInfo {private: char *name; int age; public: PersonInfo ( char *n, int a ) { name = new char[strlen( n )+ 1]; strcpy( name, n ); age = a; }

CS SJAllan Chapter Using this – Program PersonInfo ( const PersonInfo &obj ) // Copy constructor { name = new char[strlen(obj.name)+ 1]; strcpy(name, obj.name); age = obj.age; } ~PersonInfo ( void ) { delete [] name; } char *getName ( void ) { return name; } int getAge ( void ) { return age; } const PersonInfo operator= ( const PersonInfo &right ) { delete [] name; name = new char[strlen( right.name ) + 1]; strcpy( name, right.name ); age = right.age; return *this; } }; // PersonInfo

CS SJAllan Chapter Using this – Program int main ( void ) {PersonInfo jim("Jim Young", 27), bob("Bob Faraday", 32), clone = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; cout << "Now the clone and Bob will change to Jim.\n"; clone = bob = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; return 0; } // main

CS SJAllan Chapter Using this – Output The Jim Object contains: Jim Young, 27 The Bob Object contains: Bob Faraday, 32 The Clone Object contains: Jim Young, 27 Now the clone and Bob will change to Jim. The Jim Object contains: Jim Young, 27 The Bob Object contains: Jim Young, 27 The Clone Object contains: Jim Young, 27

CS SJAllan Chapter Issues of Operator Overloading You can change an operator’s entire meaning when you overload it – don’t You cannot change the number of operands taken by an operator  For example, the = symbol must always be a binary operator  Likewise, ++ and -- must always be unary operators The following operators cannot overloaded  ?:..* :: sizeof

CS SJAllan Chapter Operators That can be Overloaded

CS SJAllan Chapter feetinch.h – Program #ifndef FEETINCHES_H #define FEETINCHES_H class FeetInches {private: int feet; int inches; void simplify(void); public: FeetInches( int f = 0, int i = 0 ) { feet = f; inches = i; simplify(); } void setFeet( int f ) { feet = f; }

CS SJAllan Chapter feetinch.h – Program void setInches( int i ) { inches = i; simplify(); } int getFeet(void) { return feet; } int getInches(void) { return inches; } FeetInches operator + (const FeetInches &); FeetInches operator - (const FeetInches &); FeetInches operator ++ ( void ); // Prefix ++ FeetInches operator ++ ( int ); // Postfix ++ bool operator > ( const FeetInches & ); bool operator < ( const FeetInches & ); bool operator == ( const FeetInches & ); friend ostream &operator << ( ostream &, const FeetInches & ); friend istream &operator >> ( istream &, const FeetInches & ); };// FeetInches #endif

FeetInches Why didn’t we overload the assignment ( = ) operator? CS SJAllan Chapter 14 46

simplify 3 feet 14 inches  4 feet 2 inches 5 feet -2 inches  4 feet 10 inches CS SJAllan Chapter 14 47

CS SJAllan Chapter feetinc.cpp – Program #include #include "feetinch.h" void FeetInches::simplify ( void ) {if ( inches >= 12 ) {feet += (inches / 12); inches %= 12; } // if else if ( inches < 0 ) {feet -= ( ( abs( inches ) / 12 ) + 1 ); inches = 12 - ( abs( inches ) % 12 ); } // else } // FeetInches::simplify

CS SJAllan Chapter feetinc.cpp – Program FeetInches FeetInches::operator + ( const FeetInches &right ) { FeetInches temp; temp.inches = inches + right.inches; temp.feet = feet + right.feet; temp.simplify(); return temp; } // FeetInches::operator + FeetInches FeetInches::operator - ( const FeetInches &right ) {FeetInches temp; temp.inches = inches - right.inches; temp.feet = feet - right.feet; temp.simplify(); return temp; } // FeetInches::operator -

CS SJAllan Chapter feetmain.cpp – Program #include #include "feetinc2.h“ using namespace std; int main ( void ) {FeetInches first, second, third; int f, i; cout << "Enter a distance in feet and inches: "; cin >> f >> i; first.setData(f, i); cout << "Enter another distance in feet and inches: "; cin >> f >> i; second.setData(f, i); third = first + second; cout << "First + Second = "; cout << third.getFeet() << " feet, "; cout << third.getInches() << " inches.\n"; third = first - second; cout << "First - Second = "; cout << third.getFeet() << " feet, "; cout << third.getInches() << " inches.\n"; return 0; } // main

CS SJAllan Chapter feetmain.cpp – Output Enter a distance in feet and inches: 6 5 [Enter] Enter another distance in feet and inches: 3 10 [Enter] First + Second = 10 feet, 3 inches. First - Second = 2 feet, 7 inches.

CS SJAllan Chapter Note: No return type is specified in the function header for the previous example  Because it is a FeetInches -to- double conversion function, it will always return a double

CS SJAllan Chapter Overloading the Prefix ++ Operator FeetInches FeetInches::operator ++ ( void ) { ++inches; simplify(); return *this; } // FeetInches::operator ++

What is Output? int num 4; cout << num++; int num = 4; Cout << ++num; CS SJAllan Chapter

CS SJAllan Chapter Overloading the Postfix ++ Operator FeetInches FeetInches::operator ++ ( int ) { FeetInches temp( feet, inches ); inches++; simplify(); return temp; } // FeetInches::operator++

CS SJAllan Chapter Overloading Relational Operators if (distance1 < distance2) { … code … } // if

CS SJAllan Chapter Overloading Relational Operators bool FeetInches:: operator > ( const FeetInches &right ) { if (feet > right.feet) return true; else if (feet == right.feet && inches > right.inches) return true; else return false; } // FeetInches::operator >

CS SJAllan Chapter Overloading the == Operator bool FeetInches::operator == ( const FeetInches &right ) { if ( feet == right.feet && inches == right.inches ) return true; else return false; } // FeetInches::operator ==

CS SJAllan Chapter Overloading the << Operator ostream &operator << ( ostream &strm, FeetInches &obj ) { strm << obj.feet << " feet, " << obj.inches << " inches"; return strm; } // operator <<

CS SJAllan Chapter Overloading the >> Operator istream &operator >> ( istream &strm, FeetInches &obj ) { cout << "Feet: "; strm >> obj.feet; cout << "Inches: "; strm >> obj.inches; return strm; } // operator >>

CS SJAllan Chapter Overloading the [ ] Operator In addition to the traditional operators, C++ allows you to change the way the [ ] (subscript) symbols work Must consider constructor, destructor Overloaded [ ] returns a reference to the object, and not the object itself

CS SJAllan Chapter Intarry.h – Program #ifndef INTARRY_H #define INTARRY_H class IntArray { private: int *aptr; int arraySize; void subscriptError( ); public: IntArray ( int ); // constructor IntArray ( const IntArray & ); //copy constructor ~IntArray ( void ); // Destructor int size ( void ) { return arraySize }; int &operator [] ( const int & ); // overloaded [ ] operator }; // IntArray #endif

CS SJAllan Chapter Intarray.cpp – Program IntArray::IntArray ( int s ) { arraySize = s; aptr = new int [s]; for ( int count = 0; count < arraySize; count++ ) *( aptr + count ) = 0; } // IntArray::IntArray IntArray::IntArray ( const IntArray &obj ) { arraySize = obj.arraySize; aptr = new int [arraySize]; assert( aptr ); for ( int count = 0; count < arraySize; count ++ ) *( aptr + count ) = *( obj.aptr + count ); } // IntArray::IntArray

CS SJAllan Chapter Intarray.cpp – Program IntArray::~IntArray ( void ) { if ( arraySize > 0 ) delete [] aptr; } // IntArray::~IntArray int &IntArray::operator [] ( const int &sub ) { if ( sub arraySize ) subscriptError(); return aptr[sub]; } // IntArray::operator []

CS SJAllan Chapter Intarray.cpp – Program void IntArray::subscriptError( void ) {cout << "ERROR: Subscript out of range.\n"; exit( 0 ); } // IntArray::subscriptError

CS SJAllan Chapter Object Conversion Special operator functions may be written to convert a class object to any other type FeetInches::operator double ( void ) { double temp = feet; temp += ( inches / 12.0 ); return temp; } // FeetInches::operator double

CS SJAllan Chapter Creating a String Class This example shows the use of a C++ class to create a string data type

CS SJAllan Chapter The MyString Class Memory is dynamically allocated for any string stored in a MyString object Strings may be assigned to a MyString object with the = operator One string may be concatenated to another with the += operator Strings may be tested for equality with the == operator

CS SJAllan Chapter MyString.h – Program #ifndef MYSTRING_H #define MYSTRING_H #include using namespace std; class MyString; // Forward declarations ostream &operator << ( ostream &, const MyString & ); istream &operator >> ( istream &, MyString & ); class MyString {private: char *str; int len; public: MyString( void ) { str = NULL; len = 0; } MyString( char * ) {len = strlen( sptr ); str = new char[len + 1 ]; strcpy( str, sptr; }

CS SJAllan Chapter MyString.h – Program MyString( MyString &right) // Copy constructor {str = new char[ right.length() + 1]; strcpy( str, right.getValue() ); len = right.length(); } ~MyString( void ) { if ( len != 0 ) delete [] str; } int length ( void ) { return len; } char *getValue ( void ) { return str; };

CS SJAllan Chapter MyString.h – Program // Overloaded operators MyString operator += ( MyString & ); char *operator += ( const char * ); MyString operator = ( MyString & ); char *operator = ( const char * ); int operator == ( MyString & ); int operator == ( const char * ); int operator != ( MyString & ); int operator != ( const char * ); bool operator > ( MyString & ); bool operator > ( const char * ); bool operator < ( const char * ); bool operator < ( MyString & ); bool operator >= ( MyString & ); bool operator >= ( const char * ); bool operator <= ( const char * ); bool operator <= ( MyString & ); friend ostream &operator << ( ostream &, MyString & ); friend istream &operator >> ( istream &, MyString & ); }; // MyString #endif

CS SJAllan Chapter MyString.cpp – Program #include #include "MyString.h" using namespace std; MyString MyString::operator = ( MyString &right ) { if ( len != 0 ) delete []; str = new char[right.length() + 1]; strcpy(str, right.getValue()); len = right.length(); return *this; } // MyString::operator = MyString MyString::operator = ( const char *right ) {if ( len != 0 ) delete [] str; len = strlen( right ); str = new char[len + 1]; strcpy( str, right ); return *this; } // MyString::operator =

CS SJAllan Chapter MyString.cpp – Program MyString MyString::operator += ( MyString &right ) {char *temp = str; str = new char[strlen(str) + right.length() + 1]; strcpy( str, temp ); strcat( str, right.getvalue() ); if ( len != 0 ) delete [] temp; len = strlen(str); return *this; } // MyString::operator +=

CS SJAllan Chapter MyString.cpp – Program (cont) char *MyString::operator += ( const char *right ) {char *temp = str; str = new char[strlen(str) + strlen(right) + 1]; strcpy( str, temp ); strcat( str, right ); if ( len != 0 ) delete [] temp; return str; } // MyString::operator += int MyString::operator == ( MyString &right ) {return !strcmp( str, right.getValue() ) ; } // MyString::operator ==

CS SJAllan Chapter MyString.cpp – Program int MyString::operator == ( const char *right ) {return !strcmp( str, right ); } // MyString::operator == int MyString::operator != ( MyString &right ) {return strcmp( str, right.getValue() ); } // MyString::operator != int MyString::operator != ( const char *right ) {return strcmp( str, right ); } // MyString::operator != bool MyString::operator >(MyString &right) {if ( strcmp( str, right.getValue() ) > 0 ) return true; else return false; } // MyString::operator >

CS SJAllan Chapter MyString.cpp – Program bool MyString::operator > ( const char *right ) {if ( strcmp( str, right ) > 0 ) return true; else return false; } // MyString::operator > bool MyString::operator < ( MyString &right ) {if ( strcmp( str, right.getValue() ) < 0 ) return true; else return false; } // MyString::operator < bool MyString::operator < ( const char *right ) {if ( strcmp( str, right ) < 0 ) return true; else return false; } // MyString::operator <

CS SJAllan Chapter MyString.cpp – Program bool MyString::operator >= ( MyString &right ) {if ( strcmp( str, right.getValue() ) >= 0 ) return true; else return false; } // MyString::operator >= bool MyString::operator >= ( const char *right ) {if ( strcmp( str, right ) >= 0 ) return true; else return false; } // MyString::operator >= bool MyString::operator <= ( MyString &right ) {if ( strcmp( str, right.getValue() ) <= 0 ) return true; else return fals; } // MyString::operator <=

CS SJAllan Chapter MyString.cpp – Program bool MyString::operator <= (const char *right ) {if ( strcmp( str, right ) <= 0 ) return true; else return false; } // MyString::operator <= ostream &operator << ( ostream &strm, const MyString &obj ) {strm << obj.str; return strm; } // operator << istream &operator >>( istream &strm, MyString &obj ) {strm.getline(obj.str, obj.len); strm.ignore(); return strm; } // operator >>

CS SJAllan Chapter MystrMain.cpp – Program #include #include "Mystring.h" using namespace std; int main ( void ) {MyString object1("This"), object2("is"); MyString object3("a test."); MyString object4 = object1; MyString object5("is only a test."); char string1[] = "a test."; cout << "Object1: " << object1 << endl; cout << "Object2: " << object2 << endl; cout << "Object3: " << object3 << endl; cout << "Object4: " << object4 << endl; cout << "Object5: " << object5 << endl;

CS SJAllan Chapter MystrMain.cpp – Program cout << "String1: " << string1 << endl; object1 += " "; object1 += object2; object1 += " "; object1 += object3; object1 += " "; object1 += object4; object1 += " "; object1 += object5; cout << "Object1: " << object1 << endl; return 0; } // main

CS SJAllan Chapter MystrMain.cpp – Output Object1: This Object2: is Object3: a test. Object4: This Object5: is only a test. String1: a test. Object1: This is a test. This is only a test.

CS SJAllan Chapter MystrMain.cpp – Program #include #include “Mystring.h“ using namespace std; int main ( void ) {MyString name1("Billy"), name2("Sue"); MyString name3("joe"); MyString string1("ABC"), string2("DEF"); cout << “name1: " << name1.getValue() << endl; cout << “name2: " << name2.getValue() << endl; cout << “name3: " << name3.getValue() << endl; cout << “string1: " << string1.getValue() << endl; cout << “string2: " << string2.getValue() << endl;

CS SJAllan Chapter MystrMain.cpp – Program if ( name1 == name2 ) cout << “name1 is equal to Name2.\n"; else cout << “name1 is not equal to Name2.\n"; if ( name3 == "joe" ) cout << “name3 is equal to joe.\n"; else cout << “name3 is not equal to joe.\n"; if ( string1 > string2 ) cout << “string1 is greater than String2.\n"; else cout << “string1 is not greater than String2.\n"; if ( string1 < string2 ) cout << “string1 is less than String2.\n"; else

CS SJAllan Chapter MystrMain.cpp – Program cout << "string1 is not less than String2.\n"; if ( string1 >= string2 ) cout << "string1 is greater than or equal to " << "string2.\n"; else cout << "string1 is not greater than or equal to " << "string2.\n"; if ( string1 >= "ABC" ) cout << "string1 is greater than or equal to " << "ABC.\n"; else cout << "string1 is not greater than or equal to " << "ABC.\n"; if ( string1 <= string2 ) cout << "string1 is less than or equal to " << "string2.\n";

CS SJAllan Chapter MystrMain.cpp – Program else cout << "string1 is not less than or equal to " << "string2.\n"; if (string2 <= "DEF") cout << "string2 is less than or equal to " << "DEF.\n"; else cout << "string2 is not less than or equal to " << "DEF.\n"; return 0; } // main

CS SJAllan Chapter MystrMain.cpp – Output name1: Billy name2: Sue name3: joe string1: ABC string2: DEF name1 is not equal to Name2. name3 is equal to joe. string1 is not greater than String2. string1 is less than String2. string1 is not greater than or equal to String2. string1 is greater than or equal to ABC. string1 is less than or equal to String2. string2 is less than or equal to DEF.

CS SJAllan Chapter Object Composition Object composition occurs when a class contains an instance of another class Creates a “has a” relationship between classes The notation for structures within structures is used with object composition