87
Chapter 14 More About Classes

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

  • View
    221

  • Download
    2

Embed Size (px)

Citation preview

Page 1: 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

Chapter 14

More About Classes

Page 2: 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

CS 1410 - 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

Page 3: 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

CS 1410 - SJAllan Chapter 14 3

Member (Instance)VariablesObject W1, W2

Page 4: 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

CS 1410 - SJAllan Chapter 14 4

Member Variable is Static

Page 5: 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

CS 1410 - 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

Page 6: 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

CS 1410 - SJAllan Chapter 14 6

testBudget.cpp – Program #include <iostream>#include <iomanip>#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

Page 7: 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

CS 1410 - SJAllan Chapter 14 7

testBudget.cpp – Programcout << 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;} // forcout << "\tTotal Budget Requests:\t$ ";cout << divisions[0].getCorpBudget() << endl;

return 0;} // main

Page 8: 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

CS 1410 - SJAllan Chapter 14 8

testBudget.cpp – Output

Enter the budget request for Division 1: 100000 [Enter]Enter the budget request for Division 2: 200000 [Enter]Enter the budget request for Division 3: 300000 [Enter]Enter the budget request for Division 4: 400000 [Enter]Here are the division budget requests:

Division 1 $ 100000.00Division 2 $ 200000.00Division 3 $ 300000.00Division 4 $ 400000.00Total Budget Requests: $ 1000000.00

Page 9: 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

CS 1410 - 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";

Page 10: 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

CS 1410 - SJAllan Chapter 14 10

A New Budget.h – Program #ifndef BUDGET_H#define BUDGET_Hclass 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

Page 11: 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

CS 1410 - SJAllan Chapter 14 11

Budget.cpp – Program

#include "budget.h"

double Budget::corpBudget = 0;

void Budget::mainOffice ( double moffice ){ corpBudget += moffice;} // Budget::mainOffice

Page 12: 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

CS 1410 - SJAllan Chapter 14 12

testBudget.cpp – Program #include <iostream>#include <iomanip>#include "Budget.h"using namespace std;

int main ( void ){ int count;

double mainOfficeRequestconst 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

Page 13: 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

CS 1410 - SJAllan Chapter 14 13

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

Page 14: 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

CS 1410 - SJAllan Chapter 14 14

testBudget.cpp – Output

Enter the main office's budget request: 100000 [Enter]

Enter the budget request for Division 1: 100000 [Enter]

Enter the budget request for Division 2: 200000 [Enter]

Enter the budget request for Division 3: 300000 [Enter]

Enter the budget request for Division 4: 400000 [Enter]

Here are the division budget requests:Division 1 $ 100000.00Division 2 $ 200000.00Division 3 $ 300000.00Division 3 $ 400000.00Total Requests (including main office): $ 1100000.00

Page 15: 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

CS 1410 - SJAllan Chapter 14 15

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

Page 16: 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

CS 1410 - SJAllan Chapter 14 16

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

Page 17: 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

CS 1410 - SJAllan Chapter 14 17

Friend Classes As mentioned before, it is possible to make

an entire class a friend of another class. class FriendClass{

…}; // FriendClassclass NewClass{ public:

friend class FriendClass;// declares entire class (Friendclass) as a friend of

this class…

}; // NewClass

Page 18: 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

CS 1410 - SJAllan Chapter 14 18

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;

Page 19: 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

CS 1410 - SJAllan Chapter 14 19

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;

Page 20: 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

CS 1410 - SJAllan Chapter 14 20

PersonInfo person1("Maria Jones-Tucker", 25);

Maria Jones-Tucker

Dynamically allocated memory

namepointer

Page 21: 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

CS 1410 - SJAllan Chapter 14 21

PersonInfo person2 = person1;

Maria Jones-Tucker

Both objects’ name members point to the same section of memory

person1’snamepointer

person2’snamepointer

Dynamically allocated memory

Page 22: 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

CS 1410 - SJAllan Chapter 14 22

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

Page 23: 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

CS 1410 - SJAllan Chapter 14 23

Programmer Defined Copy Constructor Consider the following:

PersonInfo info1( "Ann", 5 );PersonInfo info2 = info1;

info2.setName( "Jane" );

name

info1

name

info2“Ann” “Jane”

Page 24: 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

CS 1410 - SJAllan Chapter 14 24

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 modifiedPersonInfo::PersonInfo( const PersonInfo

&obj )

Page 25: 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

CS 1410 - SJAllan Chapter 14 25

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

Page 26: 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

CS 1410 - SJAllan Chapter 14 26

Operator Overloading

C++ allows you to redefine how standard operators work when used with class objects

Page 27: 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

CS 1410 - SJAllan Chapter 14 27

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

Page 28: 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

CS 1410 - SJAllan Chapter 14 28

Operator Overload – Program#include <iostream>#include <cstring>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

Page 29: 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

CS 1410 - SJAllan Chapter 14 29

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

Page 30: 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

CS 1410 - SJAllan Chapter 14 30

Operator Overload – Output

The Jim Object contains: Jim Young, 27The Bob Object contains: Bob Faraday, 32The Clone Object contains: Jim Young, 27Now the clone will change to Bob and Bob will change to Jim.The Jim Object contains: Jim Young, 27The Bob Object contains: Jim Young, 27The Clone Object contains: Bob Faraday, 32

Page 31: 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

CS 1410 - SJAllan Chapter 14 31

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 asperson3 = person2 = person1;

you must have the following prototype:PersonInfo operator= (const PersonInfo &Right);

Page 32: 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

CS 1410 - SJAllan Chapter 14 32

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

Page 33: 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

Use of this pointer

This refers to the class itself.

CS 1410 - SJAllan Chapter 14 33

Page 34: 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

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 1410 - SJAllan Chapter 14 34

Page 35: 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

You can use “this” even when it is the not requiredClass 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 1410 - SJAllan Chapter 14 35

Page 36: 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

Sometimes you need a name for yourself. “this” is that nameClass 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 1410 - SJAllan Chapter 14 36

Page 37: 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

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 1410 - SJAllan Chapter 14 37

Page 38: 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

CS 1410 - SJAllan Chapter 14 38

Using this – Program #include <iostream>#include <cstring>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; }

Page 39: 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

CS 1410 - SJAllan Chapter 14 39

Using this – ProgramPersonInfo ( 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

Page 40: 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

CS 1410 - SJAllan Chapter 14 40

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

Page 41: 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

CS 1410 - SJAllan Chapter 14 41

Using this – Output

The Jim Object contains: Jim Young, 27The Bob Object contains: Bob Faraday, 32The Clone Object contains: Jim Young, 27Now the clone and Bob will change to Jim.The Jim Object contains: Jim Young, 27The Bob Object contains: Jim Young, 27The Clone Object contains: Jim Young, 27

Page 42: 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

CS 1410 - SJAllan Chapter 14 42

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

Page 43: 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

CS 1410 - SJAllan Chapter 14 43

Operators That can be Overloaded

Page 44: 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

CS 1410 - SJAllan Chapter 14 44

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

Page 45: 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

CS 1410 - SJAllan Chapter 14 45

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

Page 46: 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

FeetInches

Why didn’t we overload the assignment ( = ) operator?

CS 1410 - SJAllan Chapter 14 46

Page 47: 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

simplify

3 feet 14 inches 4 feet 2 inches

5 feet -2 inches 4 feet 10 inches

CS 1410 - SJAllan Chapter 14 47

Page 48: 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

CS 1410 - SJAllan Chapter 14 48

feetinc.cpp – Program#include <cstdlib>#include "feetinch.h"

void FeetInches::simplify ( void ){ if ( inches >= 12 )

{ feet += (inches / 12); inches %= 12;

} // ifelse if ( inches < 0 ){ feet -= ( ( abs( inches ) / 12 ) + 1 );

inches = 12 - ( abs( inches ) % 12 );} // else

} // FeetInches::simplify

Page 49: 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

CS 1410 - SJAllan Chapter 14 49

feetinc.cpp – ProgramFeetInches 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 -

Page 50: 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

CS 1410 - SJAllan Chapter 14 50

feetmain.cpp – Program#include <iostream>#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

Page 51: 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

CS 1410 - SJAllan Chapter 14 51

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.

Page 52: 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

CS 1410 - SJAllan Chapter 14 52

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

Page 53: 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

CS 1410 - SJAllan Chapter 14 53

Overloading the Prefix ++ OperatorFeetInches FeetInches::operator ++ ( void ){ ++inches; simplify(); return *this;} // FeetInches::operator ++

Page 54: 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

What is Output?

int num 4;

cout << num++;

int num = 4;

Cout << ++num;

CS 1410 - SJAllan Chapter 14 54

4

5

Page 55: 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

CS 1410 - SJAllan Chapter 14 55

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

Page 56: 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

CS 1410 - SJAllan Chapter 14 56

Overloading Relational Operatorsif (distance1 < distance2){ … code …} // if

Page 57: 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

CS 1410 - SJAllan Chapter 14 57

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 >

Page 58: 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

CS 1410 - SJAllan Chapter 14 58

Overloading the == Operatorbool FeetInches::operator == ( const FeetInches &right ){ if ( feet == right.feet && inches == right.inches ) return true; else

return false;} // FeetInches::operator ==

Page 59: 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

CS 1410 - SJAllan Chapter 14 59

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

Page 60: 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

CS 1410 - SJAllan Chapter 14 60

Overloading the >> Operatoristream &operator >> ( istream &strm, FeetInches &obj ){ cout << "Feet: "; strm >> obj.feet; cout << "Inches: "; strm >> obj.inches;

return strm;} // operator >>

Page 61: 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

CS 1410 - SJAllan Chapter 14 61

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

Page 62: 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

CS 1410 - SJAllan Chapter 14 62

Intarry.h – Program #ifndef INTARRY_H#define INTARRY_Hclass IntArray{ private:

int *aptr;int arraySize;void subscriptError( );

public:IntArray ( int ); // constructorIntArray ( const IntArray & ); //copy constructor~IntArray ( void ); // Destructorint size ( void ) { return arraySize };int &operator [] ( const int & ); // overloaded [ ] operator

}; // IntArray#endif

Page 63: 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

CS 1410 - SJAllan Chapter 14 63

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

Page 64: 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

CS 1410 - SJAllan Chapter 14 64

Intarray.cpp – ProgramIntArray::~IntArray ( void ){ if ( arraySize > 0 )

delete [] aptr;} // IntArray::~IntArray

int &IntArray::operator [] ( const int &sub ){ if ( sub < 0 || sub > arraySize )

subscriptError(); return aptr[sub];} // IntArray::operator []

Page 65: 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

CS 1410 - SJAllan Chapter 14 65

Intarray.cpp – Program

void IntArray::subscriptError( void ){ cout << "ERROR: Subscript out of range.\n";

exit( 0 );} // IntArray::subscriptError

Page 66: 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

CS 1410 - SJAllan Chapter 14 66

Object Conversion

Special operator functions may be written to convert a class object to any other typeFeetInches::operator double ( void ){ double temp = feet;

temp += ( inches / 12.0 );return temp;

} // FeetInches::operator double

Page 67: 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

CS 1410 - SJAllan Chapter 14 67

Creating a String Class

This example shows the use of a C++ class to create a string data type

Page 68: 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

CS 1410 - SJAllan Chapter 14 68

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

Page 69: 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

CS 1410 - SJAllan Chapter 14 69

MyString.h – Program #ifndef MYSTRING_H#define MYSTRING_H#include <iostream>using namespace std;class MyString; // Forward declarationsostream &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; }

Page 70: 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

CS 1410 - SJAllan Chapter 14 70

MyString.h – ProgramMyString( 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; };

Page 71: 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

CS 1410 - SJAllan Chapter 14 71

MyString.h – Program// Overloaded operatorsMyString 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

Page 72: 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

CS 1410 - SJAllan Chapter 14 72

MyString.cpp – Program#include <cstring>#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 =

Page 73: 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

CS 1410 - SJAllan Chapter 14 73

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 +=

Page 74: 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

CS 1410 - SJAllan Chapter 14 74

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

Page 75: 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

CS 1410 - SJAllan Chapter 14 75

MyString.cpp – Programint 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 >

Page 76: 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

CS 1410 - SJAllan Chapter 14 76

MyString.cpp – Programbool 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 <

Page 77: 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

CS 1410 - SJAllan Chapter 14 77

MyString.cpp – Programbool 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 <=

Page 78: 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

CS 1410 - SJAllan Chapter 14 78

MyString.cpp – Programbool 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 >>

Page 79: 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

CS 1410 - SJAllan Chapter 14 79

MystrMain.cpp – Program#include <iostream>#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;

Page 80: 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

CS 1410 - SJAllan Chapter 14 80

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

Page 81: 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

CS 1410 - SJAllan Chapter 14 81

MystrMain.cpp – Output

Object1: This Object2: isObject3: a test.Object4: This Object5: is only a test.String1: a test.Object1: This is a test. This is only a test.

Page 82: 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

CS 1410 - SJAllan Chapter 14 82

MystrMain.cpp – Program #include <iostream>#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;

Page 83: 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

CS 1410 - SJAllan Chapter 14 83

MystrMain.cpp – Programif ( 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

Page 84: 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

CS 1410 - SJAllan Chapter 14 84

MystrMain.cpp – Programcout << "string1 is not less than String2.\n";

if ( string1 >= string2 )cout << "string1 is greater than or equal to " << "string2.\n";

elsecout << "string1 is not greater than or equal to " << "string2.\n";

if ( string1 >= "ABC" )cout << "string1 is greater than or equal to " << "ABC.\n";

elsecout << "string1 is not greater than or equal to " << "ABC.\n";

if ( string1 <= string2 )cout << "string1 is less than or equal to " << "string2.\n";

Page 85: 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

CS 1410 - SJAllan Chapter 14 85

MystrMain.cpp – Program

elsecout << "string1 is not less than or equal to " << "string2.\n";

if (string2 <= "DEF")cout << "string2 is less than or equal to " << "DEF.\n";

elsecout << "string2 is not less than or equal to " << "DEF.\n";

return 0;} // main

Page 86: 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

CS 1410 - SJAllan Chapter 14 86

MystrMain.cpp – Output name1: Billyname2: Suename3: joestring1: ABCstring2: DEFname1 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.

Page 87: 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

CS 1410 - SJAllan Chapter 14 87

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