Top Banner
Classes Classes Representing Non-Trivial Objects Representing Non-Trivial Objects
25

Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Jan 05, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

ClassesClasses

Representing Non-Trivial ObjectsRepresenting Non-Trivial Objects

Page 2: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

ProblemProblem

Write a program that reads a temperature Write a program that reads a temperature (either Fahrenheit or Celsius), and (either Fahrenheit or Celsius), and displays that same temperature in both displays that same temperature in both scales.scales.

Page 3: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Preliminary AnalysisPreliminary Analysis

An object must be directly representable An object must be directly representable using a single type.using a single type.

A temperature has two attributes:A temperature has two attributes:– its its magnitudemagnitude (a double), and (a double), and

– its its scalescale (a character). (a character).

When an object cannot be directly When an object cannot be directly represented by any of the available types, represented by any of the available types, build a classbuild a class!!

Page 4: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Building ClassesBuilding Classes

Begin by defining variables to store the attributes of the Begin by defining variables to store the attributes of the object being represented (a temperature) in a class header object being represented (a temperature) in a class header file (e.g., Temperature.h):file (e.g., Temperature.h):

double myMagnitude;char myScale;

Pretending that Pretending that we arewe are the temperature object, the temperature object, we begin the name of each attribute with the we begin the name of each attribute with the prefix prefix my, to reinforce this , to reinforce this internal perspectiveinternal perspective..

Page 5: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Building ClassesBuilding Classes

We then wrap these variables in a class We then wrap these variables in a class declaration:declaration:class Temperature{ public: private: double myMagnitude; char myScale;};

When declared within a class declaration, such When declared within a class declaration, such variables are called class variables are called class data membersdata members..

Page 6: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Information HidingInformation HidingClasses have a Classes have a public sectionpublic section and a and a private sectionprivate section..

Items declared in the public section are Items declared in the public section are accessibleaccessible to users of the class; items declared in the private section are to users of the class; items declared in the private section are inaccessibleinaccessible to to users of the class.users of the class.

Data members should go in the Data members should go in the privateprivate section, to prevent programmers from writing programs that access data members directly. section, to prevent programmers from writing programs that access data members directly.

Page 7: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Why?Why?Software must often be updated. Software must often be updated.

A program that uses a class should still work after the class has been updated.A program that uses a class should still work after the class has been updated.

Updating a class may require that its data members be replaced by others.Updating a class may require that its data members be replaced by others.

If a program accesses class data members directly, then that program “breaks” if they are replaced.If a program accesses class data members directly, then that program “breaks” if they are replaced.

This increases software maintenance costs.This increases software maintenance costs.

Page 8: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

A New TypeA New Type

A programmer can now write:A programmer can now write:

#include “Temperature.h” // class Temperature...Temperature aTemp;

and object and object aTemp can be visualized as follows: can be visualized as follows:

myMagnitude

myScale

aTemp

The data members The data members myMagnitude and and myScale within within aTemp are are uninitialized.uninitialized.

Page 9: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Operations and MessagesOperations and MessagesOperations on a class object are usually implemented as class Operations on a class object are usually implemented as class function membersfunction members..

A call to a function member:A call to a function member:

Object.Function()

can be thought of as the caller sending the object can be thought of as the caller sending the object Object a message named a message named Function..

The definition of a function member details what The definition of a function member details what Object does in response to the message. does in response to the message.

Page 10: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Example: OutputExample: Output

Suppose we want to be able to display the Suppose we want to be able to display the value of a value of a Temperature object by sending object by sending it the it the Print() message: message:aTemp.Print(cout);

Using the internal perspective (where I am the Using the internal perspective (where I am the Temperature object receiving the message): object receiving the message):

Specification:Specification:Receive: Receive: outout, an ostream., an ostream.Output: Output: myMagnitudemyMagnitude and and myScalemyScale, via , via outout..Passback: Passback: outout, containing the new values., containing the new values.

Page 11: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Function Member Function Member DefinitionsDefinitions

void Temperature::Print(ostream & out) const{ out << myMagnitude << myScale;}

The function returns nothing, so its return-type is The function returns nothing, so its return-type is void..

The full name The full name Temperature::Print() tells the compiler this is a tells the compiler this is a Temperature function member. function member.

The caller passes and changes an The caller passes and changes an ostream argument, so we need a reference parameter to store this argument, so we need a reference parameter to store this argument.argument.

Function members that change no data members should be defined as Function members that change no data members should be defined as const function members. function members.

In Temperature.cpp:In Temperature.cpp:

Page 12: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Function Member Function Member PrototypesPrototypes

class Temperature{ public: void Print(ostream & out) const; private: double myMagnitude; char myScale;};

By declaring the prototype within the class, we tell the compiler that By declaring the prototype within the class, we tell the compiler that class class Temperature has a function member named has a function member named Print(), and that , and that Temperature objects should “understand” the objects should “understand” the Print() message. message.

Most function prototypes go in the class Most function prototypes go in the class public sectionpublic section..

Page 13: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

ProblemProblem

At present, a At present, a Temperature declaration: declaration:

Temperature aTemp;

leaves leaves aTemp’s data members of uninitialized.’s data members of uninitialized.

To auto-initialize them to a default value (e.g., To auto-initialize them to a default value (e.g., 0C), we can use a special function called a ), we can use a special function called a constructorconstructor..

Page 14: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

ConstructorsConstructorsA constructor function is a class function member whose task is to initialize the class data members.A constructor function is a class function member whose task is to initialize the class data members.

Because they just initialize data members, they don’t return anything, and so their specification is often given as a Because they just initialize data members, they don’t return anything, and so their specification is often given as a postconditionpostcondition (a boolean expression that is true when the function terminates). (a boolean expression that is true when the function terminates).

Default Constructor Specification:Default Constructor Specification:

Postcondition: Postcondition: myMagnitudemyMagnitude == 0.0 && == 0.0 && myScalemyScale == ‘C’. == ‘C’.

Page 15: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Constructor DefinitionConstructor Definition

Since it returns nothing, a constructor has Since it returns nothing, a constructor has no return typeno return type (not even (not even void).).

The name of a constructor is always the name of the class (in this case The name of a constructor is always the name of the class (in this case Temperature()).).

As a function member of class As a function member of class Temperature, its full name is , its full name is Temperature::Temperature()..

Temperature::Temperature(){ myMagnitude = 0.0; myScale = ‘C’;}

Page 16: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Constructor PrototypeConstructor Prototypeclass Temperature{ public: Temperature(); void Print(ostream & out) const; private: double myMagnitude; char myScale;};

Since they specify the first thing a user of the class needs to Since they specify the first thing a user of the class needs to know (i.e., how to define class objects), constructor know (i.e., how to define class objects), constructor prototypes are usually the prototypes are usually the firstfirst function members listed in function members listed in the public section of the class.the public section of the class.

Page 17: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Object DefinitionsObject Definitions

A programmer can now write:A programmer can now write:

Temperature aTemp;

and object and object aTemp can be visualized as follows: can be visualized as follows:

The class constructor is automatically called whenever a class The class constructor is automatically called whenever a class object is defined.object is defined.

C

myMagnitude

myScale

aTemp 0.0

Page 18: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

TestingTesting

To test this much, we can write:To test this much, we can write:// ... documentation// ... other #includes#include “Temperature.h”

int main(){ Temperature aTemp;

aTemp.Print(cout); // displays 0C}

Page 19: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Problem 2Problem 2

At present, we can only initialize a At present, we can only initialize a Temperature to a default value:Temperature to a default value:

Temperature aTemp;

We have no means of initializing a We have no means of initializing a Temperature to any other value.to any other value.

To initialize a To initialize a Temperature to a particular to a particular value (e.g., value (e.g., 98.6F), we can overload the ), we can overload the constructorconstructor with a second definition. with a second definition.

Page 20: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Constructor 2Constructor 2To overload the constructor, we just provide a second definition (and prototype) that differs from all other constructors in at least one parameter.To overload the constructor, we just provide a second definition (and prototype) that differs from all other constructors in at least one parameter.

To initialize the data members of our class, this second constructor must receive the initial values via its parameters.To initialize the data members of our class, this second constructor must receive the initial values via its parameters.

Constructor 2 Specification:Constructor 2 Specification:Receive: Receive: magnitudemagnitude, a double; , a double; scalescale, a char., a char.Precondition: Precondition: scalescale == ‘F’ || == ‘F’ || scalescale == ‘C’. == ‘C’.Postcondition: Postcondition: myMagnitudemyMagnitude == == magnitudemagnitude && && myScalemyScale == == scalescale..

Page 21: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Constructor 2 DefinitionConstructor 2 Definition

As before, we place this (second) constructor definition in the As before, we place this (second) constructor definition in the implementation file -- Temperature.cpp.implementation file -- Temperature.cpp.

Temperature::Temperature(double magnitude, char scale){ assert(scale == ‘F’ || scale == ‘C’); myMagnitude = magnitude; myScale = scale;}

Page 22: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Constructor 2 PrototypeConstructor 2 Prototypeclass Temperature{ public: Temperature(); Temperature(double magnitude, char scale); void Print(ostream & out) const; private: double myMagnitude; char myScale;};

The same name can be used to define different The same name can be used to define different functions, provided the functions, provided the signaturesignature (the list of the (the list of the parameter types) of each function is different.parameter types) of each function is different.

Page 23: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

Object DefinitionsObject Definitions

A programmer can now write:A programmer can now write:

Temperature temp1, temp2(98.6, ‘F’);

and and temp1 and and temp2 are defined as follows: are defined as follows:

The compiler uses the number of arguments in a declaration to The compiler uses the number of arguments in a declaration to decide which constructor to use in initializing an object.decide which constructor to use in initializing an object.

C

myMagnitude

myScale

temp1 0.0

F

myMagnitude

myScale

temp2 98.6

Page 24: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

TestingTesting

To test this much, we can write:To test this much, we can write:// ... documentation// ... other #includes#include “Temperature.h”

int main(){ Temperature temp1, temp2(98.6, ‘F’);

temp1.Print(cout); // displays 0C cout << endl; temp2.Print(cout); // displays 98.6F}

Page 25: Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.

SummarySummaryWhen no existing type is appropriate to represent an object, the C++ When no existing type is appropriate to represent an object, the C++

classclass allows a type to be created. allows a type to be created.

Classes have Classes have data membersdata members (private), and (private), and function membersfunction members (public).(public).

In its definition, a function member’s name must be preceded by In its definition, a function member’s name must be preceded by the the name of the classname of the class and the and the scope operatorscope operator (::). (::).

Class Class constructor functionsconstructor functions allow class objects to be initialized to allow class objects to be initialized to default, or to specified values.default, or to specified values.