1 introduction to classes. c++: classes & objects - 12 procedural and object-oriented...

87
1 Introduction to Introduction to Classes Classes

Post on 20-Dec-2015

227 views

Category:

Documents


1 download

TRANSCRIPT

1

Introduction to Introduction to ClassesClasses

C++: Classes & Objects - 1 2

Procedural and Procedural and Object-Oriented ProgrammingObject-Oriented Programming

Procedural programming focuses on the process/actions that occur in a program

Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of abstract data types (ADTs) that encapsulate the data and its functions

C++: Classes & Objects - 1 3

Limitations of Procedural ProgrammingLimitations of Procedural Programming If the data structures change, many functions

must also be changedData and functions are separate entities

As programs become larger and more complex, the separation of a program’s data and the code that operates on the data can lead to problemsdifficult to understand and maintaindifficult to modify and extendeasy to break

C++: Classes & Objects - 1 4

Object Oriented ProgrammingObject Oriented Programming OOP programming is centered on creating

objects

An object is a software entity that contains both data and procedures

Conceptually, it is a self-contained unit consisting of attributes (data) and procedures (methods or functions)

The data is known as the object’s attributes

The procedures that an object performs are called member methods or functions

C++: Classes & Objects - 1 5

Classes and ObjectsClasses and Objects A class is like a blueprint (not real) and

objects are like houses built from the blueprint (real things)An object is an instance of a class

C++: Classes & Objects - 1 6

More on ObjectsMore on Objects encapsulation: combining data and code into a single

object

data hiding: restricting access to the data of an object from code that is outside the object

public interface: members of an object that are available outside of the object. This allows the object to provide access to some data and

functions without sharing its internal details and design, and provides some protection from data corruption

What are the public interfaces of a car? What do they hide?

C++: Classes & Objects - 1 7

Class and Object ExampleClass and Object Example

House class

Ranch house object

Town houseobject

Two family houseobject

Each house has windows, doors, floors,

etc.

How many of each and what

type differentiate each object

C++: Classes & Objects - 1 8

Class and Object ExampleClass and Object Example

Bank Account

Savings Account object

Checking Accountobject

Mutual Fundobject

What might these three

accounts have in common?

How might they differ?

C++: Classes & Objects - 1 9

Introduction to ClassesIntroduction to Classes Objects are created from a class

A class has no memory allocated to it while an object does

The first letter of the class is capitalized to show it is not a variable name

Format:class ClassName{

declaration;declaration;

};

C++: Classes & Objects - 1 10

Class ExampleClass Example

Attributes

Methods/Functions

C++: Classes & Objects - 1 11

Access SpecifiersAccess Specifiers Used to control access to members of the

classpublic: can be accessed by functions

outside of the classprivate: can only be called by or

accessed by functions that are members of the class

Attributes are generally made private so they can not be directly accessed outside of the object

Private attributes can only be accessed through the public functions

C++: Classes & Objects - 1 12

Class ExampleClass ExamplePrivate Members

Public Members

In order for an outside program to set the private attribute width of an object, the function setWidth() must be invoked

C++: Classes & Objects - 1 13

More on Access SpecifiersMore on Access Specifiers

Can be listed in any order in a class Can appear multiple times in a class

Best to group all private declarations in one spot and all public declarations in their own spot

If not specified, the default is privateIt is best to explicitly declare attributes as private even though it’s not necessary

C++: Classes & Objects - 1 14

Using Using constconst With Member Functions With Member Functionsconst appearing after the parentheses in

a member function declaration specifies that the function will not change any data in the calling object.This can act as a check on the function so

that if code was inserted to change an attribute, the compiler will generate an error

C++: Classes & Objects - 1 15

Defining a Member FunctionDefining a Member Function When defining a member function:

Put function prototype in class declaration Code for the function is written outside the class

Define function using class name and scope resolution operator (::)

void Rectangle::setWidth(double w){ width = w;}

int Rectangle::getLength()const{ return length;}

int Rectangle::getArea()const{ return length*width;}

C++: Classes & Objects - 1 16

Accessors and MutatorsAccessors and Mutators

Mutator: a member function that stores a value in a private member variable, or changes its value in some way (setLength and setWidth)

Accessor: function that retrieves a value from a private member variable. Accessors do not change an object's data, so they

should be marked const (getLength and getWidth)

C++: Classes & Objects - 1 17

Defining an Instance of a ClassDefining an Instance of a Class An object is an instance of a class

Classname objectname; Defined as (instantiated as):

Rectangle r; Access members using dot operator:

r.setWidth(5.2);cout << r.getWidth(); int x = r.getArea();Compiler error if attempt to access private

member using dot operator outside the class Inside the class functions, the member attributes

are directly accessible

C++: Classes & Objects - 1 18

C++: Classes & Objects - 1 19

C++: Classes & Objects - 1 20

A Rectangle object named box is

created, the values in length and width

are garbage

In lines 83 and 84, width and

length are assigned real

values

C++: Classes & Objects - 1 21

C++: Classes & Objects - 1 22

Multiple Objects of the same ClassMultiple Objects of the same Class You can define more than one object of the same class within a program Each object gets its own name or is part of an array

You precede the function name with the name of the name of the object to uniquely identify it (see 13-2)

Rectangle kitchen; // To hold kitchen dimensions Rectangle bedroom; // To hold bedroom dimensions // Get the kitchen dimensions. cout << "What is the kitchen's length? "; cin >> number; // Get the length kitchen.setLength(number); // Store in kitchen object cout << "What is the kitchen's width? "; cin >> number; // Get the width kitchen.setWidth(number); // Store in kitchen object

// Get the bedroom dimensions. cout << "What is the bedroom's length? "; cin >> number; // Get the length bedroom.setLength(number); // Store in bedroom object cout << "What is the bedroom's width? "; cin >> number; // Get the width bedroom.setWidth(number);

C++: Classes & Objects - 1 23

Avoiding Stale DataAvoiding Stale Data An object’s state is the data that is stored in the

object’s attributes at any given moment Some data is the result of a calculation.

In the Rectangle class the area of a rectangle is calculated by length * width

If we were to use an area variable here in the Rectangle class, its value would be dependent on the length and the width.

If we change length or width without updating area, then area would become stale.

To avoid stale data, it is best to calculate the value of that data within a member function rather than store it in a variable.

C++: Classes & Objects - 1 24

Pointer to an ObjectPointer to an Object Can define a pointer to an object:Rectangle *rPtr; //Rectangle pointer

Rectangle myRectangle; //Rectangle Object

rPtr = & myRectangle Can access public members via pointer using

the -> operator:rPtr = &otherRectangle;

rPtr->setLength(12.5);

cout << rPtr->getLenght() << endl;

C++: Classes & Objects - 1 25

Dynamically Allocating an ObjectDynamically Allocating an Object

We can also use a pointer to dynamically allocate an object.

C++: Classes & Objects - 1 26

Why Have Private Members?Why Have Private Members?

Making data members private provides data protection

Data can be accessed only through public functions

Public functions define the class’s public interface

C++: Classes & Objects - 1 27

Code outside the class must use the class's public member functions to interact with the object. Can provide validation.

Why Have Private Members?Why Have Private Members?

Void Rectangle:: setWidth(double w)

{

if (w>=0) width =w;

else

{cout<<“Invalid width\n”;

exit(EXIT_FAILURE);

}

}

Parameter is tested and validated before being assigned

C++: Classes & Objects - 1 28

Separating Specification from ImplementationSeparating Specification from Implementation

Place class declaration in a header file that serves as the class specification file. Name the file ClassName.h, for example, Rectangle.h

Place member function definitions in the implementation file ClassName.cpp, for example, Rectangle.cpp File should #include the class specification file

Programs that use the class must #include the class specification file, and be compiled and linked with the member function definitions

C++: Classes & Objects - 1 29

Separating Specification from ImplementationSeparating Specification from Implementation Provides flexibility

A class can be given to another programmer without sharing the source code by providing the compiled object file for the class’s implementation

The other programmer inserts the necessary #include directive into his program, compiles it and links it with your class’s object file

When a class’s member functions must be modified, it is only necessary to modify the implementation file and recompile it into a new object file

Programs that use the class don’t have to be completely recompiled, just linked with the new object file

C++: Classes & Objects - 1 30

Rectangle.hRectangle.h// Specification file for the Rectangle class.#ifndef RECTANGLE_H#define RECTANGLE_H

// Rectangle class declaration.

class Rectangle{ private: double width; double length; public: void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const;};#endif

This directive tells the preprocessor to see if a

constant named RECTANGLE_H has not been previously created with a #define directive

If the RECTANGLE_H constant has not been defined, these lines are

included in the program. Otherwise, these lines are not included in the

program

The first included line defines the RECTANGLE_H

constant. If this file is included again, the include guard will skip its contents

C++: Classes & Objects - 1 31

Rectangle.hRectangle.h

Preprocessor directives #ifndef and #endif include guard – prevents the header file from

accidentally being included more than once by an #include in a main

Could have two includes, where second include specifies a .h files that the first include already specified

#ifndef – if not defined

C++: Classes & Objects - 1 32

Rectangle.cppRectangle.cpp The implementation file contains the member functions of the class The first line is #include “Rectangle.h”

The filename is enclosed in double quotation marks; this indicates that the file is in the current project directory

The angled brackets < > are used to include files that are found in the compiler’s include file directory – this is where all of the standard C++ header files are located

The remaining code consists of the member functions In Code::blocks or Dev C++ you can create a project with 3 separate files

and then build and run the main program On UNIX you can compile all the cpp file on one line and then run the

resulting executable g++ RectangleMain.cpp Rectangle.cpp –o RectangleRun

You can also compile Rectangle cpp into an object file (Rectangle.o) once it is set using g++ -c Rectangle.cpp and then include it with the main on the full compile g++ -c RectangleMain.cpp Rectangle.o –o RectangleRun

C++: Classes & Objects - 1 33

Rectangle Specification & ImplementationRectangle Specification & Implementation// Rectangle.h#ifndef RECTANGLE_H#define RECTANGLE_H

// Rectangle class declaration.

class Rectangle{ private: double width; double length; public: void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const;};

#endif

//RectangleMain.cpp// This program uses the Rectangle class, which is declared in// the Rectangle.h file. The member Rectangle class's member// functions are defined in the Rectangle.cpp file. This program// should be compiled with those files in a project.#include <iostream>#include "Rectangle.h" // Needed for Rectangle classusing namespace std;

int main(){ Rectangle box; // Define an instance of the Rectangle class double rectWidth; // Local variable for width double rectLength; // Local variable for length

// Get the rectangle's width and length from the user. cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> rectWidth; cout << "What is the length? "; cin >> rectLength;

// Store the width and length of the rectangle // in the box object. box.setWidth(rectWidth); box.setLength(rectLength);

// Display the rectangle's data. cout << "Here is the rectangle's data:\n"; cout << "Width: " << box.getWidth() << endl; cout << "Length: " << box.getLength() << endl; cout << "Area: " << box.getArea() << endl; return 0;}

C++: Classes & Objects - 1 34

Rectangle Specification & ImplementationRectangle Specification & Implementation// Rectangle.cpp

#include "Rectangle.h" // Needed for the Rectangle class#include <iostream> // Needed for cout#include <cstdlib> // Needed for the exit functionusing namespace std;

//***********************************************************// setWidth sets the value of the member variable width. *//***********************************************************void Rectangle::setWidth(double w){ if (w >= 0) width = w; else { cout << "Invalid width\n"; exit(EXIT_FAILURE); }}

//***********************************************************// setLength sets the value of the member variable length. *//***********************************************************void Rectangle::setLength(double len){ if (len >= 0) length = len; else { cout << "Invalid length\n"; exit(EXIT_FAILURE); }}

//***********************************************************// getWidth returns the value in the member variable width. *//***********************************************************double Rectangle::getWidth() const{ return width;}

//*************************************************************// getLength returns the value in the member variable length. *//*************************************************************double Rectangle::getLength() const{ return length;}

//************************************************************// getArea returns the product of width times length. *//************************************************************double Rectangle::getArea() const{ return width * length;}

C++: Classes & Objects - 1 35

Rectangle Specification & ImplementationRectangle Specification & Implementation

Rectangle.cpp (Implementation file)

Rectangle.h (Specification file)

RectangleMain.cpp (Main Program file)

RectangleMain.cpp is compiled

Rectangle.h is included

Rectangle.obj(Object file)

RectangleMain.obj(Object file)

Rectangle.h is included

Rectangle.cpp is compiled

RectangleMain.exe(Executabel file)

Rectangle.obj and RectangleMain.obj are linked and RectangleRun.exe is created

C++: Classes & Objects - 1 36

Inline Member FunctionsInline Member Functions When a member function is defined in the

declaration of a class, it is called an inline functionNo need to use the scope resolution operator and

class name in the function headerSome member functions can be inline while others

can be in a specification file outside the class declaration

Inline appropriate for short function bodies:int getWidth() const { return width; }

C++: Classes & Objects - 1 37

Inline Member FunctionsInline Member Functions In order to call a function from a class specification

file, a lot of time consuming overhead occurs that can add up when a function is called many times The function’s return address in the program and the value

of the arguments are stored in the stack Local variables are created and a location is reserved for

the function’s return value Inline functions are compiled differently than other

functions Inline expansion – the compiler replaces the call to an inline

function with the code of the function itself eliminating the external function call overhead

However, because the inline function’s code can appear multiple times the size of the program can increase which can decrease system performance when paging is used

C++: Classes & Objects - 1 38

Rectangle Class with Inline Member FunctionsRectangle Class with Inline Member Functions

1 // Specification file for the Rectangle class 2 // This version uses some inline member functions. 3 #ifndef RECTANGLE_H 4 #define RECTANGLE_H 5 6 class Rectangle 7 { 8 private: 9 double width;10 double length;11 public:12 void setWidth(double);13 void setLength(double);14 15 double getWidth() const16 { return width; }17 18 double getLength() const19 { return length; }20 21 double getArea() const22 { return width * length; }23 };24 #endif

Inline functions

C++: Classes & Objects - 1 39

ConstructorsConstructors Member function that is automatically called when

an object is created

Purpose is to initialize an object’s attributes at the time the object is created. This way, object variables never have invalid values

Constructor function name is class nameRectangle::Rectangle(parameters) { … } In class declaration under public methods -Rectangle(parameters)

In class specification - Rectangle(parameters)

Has no return type, not even void

C++: Classes & Objects - 1 40

C++: Classes & Objects - 1 41

C++: Classes & Objects - 1 42

C++: Classes & Objects - 1 43

Default ConstructorsDefault Constructors A default constructor is a constructor that takes no

arguments. If you write a class with no constructor at all, when the class

is compiled C++ will write a default constructor for you, one that does nothing Rectangle::Rectangle() { } This is not a wise thing to do as the class variables will not be

initialized properly. It’s best to write a constructor with no arguments and make default assignments to the class variables

A simple instantiation of a class (with no arguments) calls the default constructor e.g., Rectangle r;

recptr = new Rectangle; creates an object and executes the deafult constructor Rectangle *recptr; does not create an object so the

constructor is not executed.

C++: Classes & Objects - 1 44

Default ConstructorsDefault Constructors If you have a non-default constructor without

a default and try to create an object with no arguments, the code won’t compileThe default constructor will only be created if

there are no other constructors. Once there is one non-default constructor, you must explicitly create the default constructor if you need it

C++: Classes & Objects - 1 45

Passing Arguments to ConstructorsPassing Arguments to Constructors To create a constructor that takes arguments:

indicate parameters in prototype:Rectangle(double, double);

Use parameters in the definition:

Rectangle::Rectangle(double w, double len){ width = w; length = len;}

You can pass arguments to the constructor when you create an object:

Rectangle r(10, 5);

C++: Classes & Objects - 1 46

Classes with No Default ConstructorClasses with No Default Constructor

When all of a class's constructors require arguments, then the class has NO default constructor.

When this is the case, you must pass the required arguments to the constructor when creating an object.

C++: Classes & Objects - 1 47

Pointers and ObjectsPointers and Objects To create an object with pointers and call the

member functions, follow the code below //rectWidth and rectLength are read in earlier

Rectangle *box;

box = new Rectangle(rectWidth,rectLength);

// Display the rectangle's data.

cout << "Here is the rectangle's data:\n";

cout << "Width: " << box->getWidth() << endl;

cout << "Length: " << box->getLength() << endl;

cout << "Area: " << box->getArea() << endl;

C++: Classes & Objects - 1 48

Default Arguments with Default Arguments with ConstructorsConstructors

A default value can be specified in the constructor header using inline code

class Rectangle

{

private:

double width;

double length;

public:

Rectangle();

Rectangle::Rectangle(double w, double l=100)

{ width = w;

length= l;

}

};

Which is the called in main by Rectangle box (rectWidth);

C++: Classes & Objects - 1 49

Default Arguments with Default Arguments with ConstructorsConstructors

If not using inline code, then do as follows:In Rectangle.h public:

Rectangle(double, double l=100.0);

In Rectangle.cppRectangle::Rectangle(double w, double l)

{

width = w;

length= l;

}

Which is the called in main by Rectangle box (rectWidth);

This will automatically substitute 100 for length

The value of 100 can be overridden by calling Rectangle box (rectWidth,rectLength); in main

C++: Classes & Objects - 1 50

DestructorsDestructors Member function automatically called when an

object is destroyed Destructor name is ~classname, e.g., ~Rectangle()

In class specification file include Rectangle::~Rectangle() { cout<<"Destructor is running"<<endl;}

Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be

overloaded If constructor allocates dynamic memory,

destructor should release it

C++: Classes & Objects - 1 51

DestructorsDestructors Including a destructor prototype in Rectangle.h

and function in Rectangle.cpp will cause the destructor to execute when main is complete

This program will calculate the area of a

rectangle. What is the width? 23

What is the length? 12

Here is the rectangle's data:

Width: 23

Length: 12

Area: 276

Destructor is running

C++: Classes & Objects - 1 52

InventoryItem.hInventoryItem.h

C++: Classes & Objects - 1 53

InventoryItem.hInventoryItem.h

C++: Classes & Objects - 1 54

C++: Classes & Objects - 1 55

Constructors, Destructors, and Constructors, Destructors, and Dynamically Allocated ObjectsDynamically Allocated Objects

When an object is dynamically allocated with the new operator, its constructor executes:

Rectangle *r = new Rectangle(10, 20);

When the object is destroyed, its destructor executes:

delete r;

C++: Classes & Objects - 1 56

Overloading ConstructorsOverloading Constructors

A class can have more than one constructor

Overloaded constructors in a class must have different parameter lists:Rectangle();Rectangle(double);

Rectangle(double, double);

C++: Classes & Objects - 1 57

Overloading ConstructorsOverloading Constructors// *********************************************************// Default Constructor *//**********************************************************Rectangle::Rectangle(){ width =0; length=0;}

// *********************************************************// Set only the width, length is fixed at 100 *//**********************************************************Rectangle::Rectangle(double w){ width =w; length=10;}

// *********************************************************// Set both class variables *//********************************************************** Rectangle::Rectangle(double w, double l) { width = w; length= l; }

C++: Classes & Objects - 1 58

From From InventoryItem.hInventoryItem.h

C++: Classes & Objects - 1 59

Only One Default Constructor Only One Default Constructor and One Destructor and One Destructor Do not provide more than one default constructor for a class

in the specification file (.h file) i.e., one that takes no arguments and one that has default arguments for all parameters

Square();

Square(int = 0); // will not compile

If you execute code Square sqr; in main, the compiler won’t know which constructor to use – the error message will state that constructor call is ambiguous

Since a destructor takes no arguments, there can only be one destructor for a class

C++: Classes & Objects - 1 60

Member Function OverloadingMember Function Overloading Non-constructor member functions can also be

overloaded:void setCost(double);

void setCost(char *);

Must have unique parameter lists as for constructors

void setcost(double c) {cost=c;}

void setcost(char *c) {cost=atof(c);}

C++: Classes & Objects - 1 61

Using Private Member FunctionsUsing Private Member Functions A private member function can only be

called by another member function

It is used for internal processing by the class, not for use outside of the class

Function is included in the private: section of the class specification file and functions in the public: section can call it

C++: Classes & Objects - 1 62

Using Private Member FunctionsUsing Private Member Functions private: void createDescription(int size, char *value) {

description = new char[size]; strcpy(description,value); }

public: InventoryItem()

{ createDescription(DEFAULT_SIZE,””); cost=0.0; units=0.0; }

C++: Classes & Objects - 1 63

Arrays of ObjectsArrays of Objects Objects can be the elements of an array:

InventoryItem inventory[40];Default constructor for object is called for each

object in the array Must use initializer list to invoke constructor

that takes arguments:InventoryItem inventory[3] =

{ "Hammer", "Wrench", "Pliers" }; If the class does not have a default

constructor, you must provide an initializer for each object in the array

C++: Classes & Objects - 1 64

Arrays of ObjectsArrays of Objects If the constructor requires more than one argument,

the initializer must take the form of a function call:

It isn't necessary to call the same constructor for each object in an array:

C++: Classes & Objects - 1 65

Arrays of ObjectsArrays of Objects If you don’t provide an initializer for all the objects in

an array, the default constructor will be called for each object that does not have an initializer. In this case, for the third object

InventoryItem inventory[3] = {“Hammer”, InventoryItem(“Wrench”,8.75,20)};

C++: Classes & Objects - 1 66

Accessing Objects in an ArrayAccessing Objects in an Array Objects in an array are referenced using

subscripts

Member functions are referenced using dot notation: inventory[2].setUnits(30);cout << inventory[2].getUnits();

C++: Classes & Objects - 1 67

C++: Classes & Objects - 1 68

OOP Case StudyOOP Case Study You are a programmer for the Home Software

Company. You have been assigned to develop a class that models the basic workings of a bank account.

The class should perform the following tasks: Save the account balance. Save the number of transactions performed on the account. Allow deposits to be made to the account. Allow withdrawals to be taken from the account. Calculate interest for the period. Report the current account balance at any time.

C++: Classes & Objects - 1 69

OOP Case StudyOOP Case Study Private Member Variables needed by the class.

Variable Description

balance A double that holds the current account balance.

interestRate A double that holds the interest rate for the period

interest A double that holds the interest earned for the current period.

transactions An integer that holds the current number of transactions

C++: Classes & Objects - 1 70

OOP Case Study - Public Member FunctionsOOP Case Study - Public Member Functions

Function Description

Constructor Takes arguments to he initially stored in the balance and interestRate members. The default value for the balance is zero and the default value for the interest rate is 0.045.

setInterestRate Takes a double argument which is stored in the interestRate member

makeDeposit Takes a double argument, which is the amount of the deposit. This argument is added to balance.

withdraw Takes a double argument which is the amount of the withdrawal. This value is subtracted from the balance, unless the withdrawal amount is greater than the balance. If this happens, the function reports an error.

calcInterest Takes no arguments. This function calculates the amount of interest for the current period, stores this value in the interest member, and then adds it to the balance member.

getInterestRate Returns the current interest rate (stored in the interestRate member).

getBalance Returns the current balance (stored in the balance member).

getInterest Returns the interest earned for the current period stored in the interest member).

getTransactions Returns the number of transactions for the current period (stored in the transactions member).

C++: Classes & Objects - 1 71

Account.hAccount.h#ifndef ACCOUNT_H#define ACCOUNT_H

class Account{private: double balance; double interestRate; double interest; int transactions; public: Account(double iRate = 0.045, double bal = 0) { balance = bal; interestRate = iRate; interest = 0; transactions = 0; }

void setInterestRate(double iRate) { interestRate = iRate; } void makeDeposit(double amount) { balance += amount; transactions++; } bool withdraw(double amount); // Defined in

Account.cpp

void calcInterest() { interest = balance * interestRate; balance += interest; } double getInterestRate() const { return interestRate; } double getBalance() const { return balance; } double getInterest() const { return interest; } int getTransactions() const { return transactions; }};#endif

C++: Classes & Objects - 1 72

Account.cppAccount.cpp// Implementation file for the Account class.#include "Account.h"

bool Account::withdraw(double amount){ if (balance < amount) return false; // Not enough in the account else { balance -= amount; transactions++; return true; }}

C++: Classes & Objects - 1 73

The Unified Modeling LanguageThe Unified Modeling Language

UML stands for Unified Modeling Language.

The UML provides a set of standard diagrams for graphically depicting object-oriented systems

C++: Classes & Objects - 1 74

UML Class DiagramUML Class Diagram

A UML diagram for a class has three main sections.

C++: Classes & Objects - 1 75

Example: A Rectangle ClassExample: A Rectangle Class

class Rectangle{ private: double width; double length; public: bool setWidth(double); bool setLength(double); double getWidth() const; double getLength() const; double getArea() const;};

C++: Classes & Objects - 1 76

UML Access Specification NotationUML Access Specification Notation

In UML you indicate a private member with a minus (-) and a public member with a plus(+).

These member variables are private.

These member functions are public.

C++: Classes & Objects - 1 77

UML Data Type NotationUML Data Type Notation To indicate the data type of a member

variable, place a colon followed by the name of the data type after the name of the variable.

- width : double- length : double

C++: Classes & Objects - 1 78

UML Function Return Type NotationUML Function Return Type Notation

To indicate the data type of a function’s parameter variable, place a colon followed by the name of the data type after the name of the variable.

To indicate the data type of a function’s return value, place a colon followed by the name of the data type after the function’s parameter list.

+ setWidth(w : double) : void

+ setWidth(w : double)

C++: Classes & Objects - 1 79

The Rectangle ClassThe Rectangle Class

C++: Classes & Objects - 1 80

Showing Constructors and DestructorsShowing Constructors and Destructors

Constructors

Destructor

No return type listed for constructors or destructors

C++: Classes & Objects - 1 81

Object Oriented DesignObject Oriented Design

Joe’s Automotive Shop service foreign cars and specializes in servicing cars made by Mercedes, Porsche and BMW. When a customer brings in a car to the shop, the manager gets the customer’s name, address and telephone number. The manager then determines the make, model and year of the car and gives the customer a service quote. The service quote shows the estimated part charges, estimated labor charges, sales tax and total estimated charges.

C++: Classes & Objects - 1 82

Object Oriented DesignObject Oriented Design Finding the classes and their responsibilities

Get a written description of the problem domain The problem domain is the set of real-world objects,

parties and major events related to the problem This may include:

Physical objects such as vehicles, machines or products Any role played by a person, such as a manager, employer,

customer, teacher, student, etc. The results of a business event such as a customer order or

service quote Recordkeeping items such as customer histories and payroll

records

C++: Classes & Objects - 1 83

Object Oriented DesignObject Oriented Design Identify all the nouns and noun phrases

Address, BMW, car, cars, customer, estimated labor charges, foreign cars, model, name, Porsche, sales tax, Joe’s Automotive shop, telephone number, shop, …

They are candidates to become classes, the list must be refined to include only those classes necessary to solve the problem

Eliminate duplicate nouns Cars/ foreign cars; Joe’s Automotive shop/shop

Some nouns may not be needed in order to solve the problem Shop, manager

Some nouns might represent objects, not classes Porsche. Mercedes, BMW, car

Some nouns might represent simple values that can be stored in a variable and do not require a class.

If the answer to both of the following questions is NO, then the noun probably represents a value that can be stored in a simple variable

Would you use a group of related values to represent the item’s state? Are there any obvious actions to be performed by the item? Address, estimate labor charges, make model, name, sales tax, telephone

number, year …

C++: Classes & Objects - 1 84

Object Oriented DesignObject Oriented Design We are left with cars, customers and service

quote as class candidates Next determine the Class’s Responsibilities

the things the class is responsible for knowing – these are the class’s attributes

The actions that the class is responsible for doing – these are the class’s member functions

C++: Classes & Objects - 1 85

Object Oriented DesignObject Oriented Design

C++: Classes & Objects - 1 86

OOD Problem Domain ExerciseOOD Problem Domain Exercise The bank offers the following types of accounts to its

customers: savings accounts, checking accounts, and money market accounts. Customers are allowed to deposit money into an account (thereby increasing its balance), withdraw money fruit an account (thereby decreasing its balance), and earn interest on the account. Each account has an interest rate.

Assume that you are writing an application that will calculate the amount of interest earned for a bank account.

a) Identify the potential classes in this problem domain.b) Refine the list to include only the necessary class or classes for this

problem.c) Identify the responsibilities of the class or classes.

C++: Classes & Objects - 1 87

OOD ExampleOOD Examplea) After eliminating duplicates, objects, and

primitive values, the potential classes are: bank, account, and customer

b) The only class needed for this particular problem is account.

c) The account class knows its balance and interest rate.

The account can calculate interest earned.