c++ classes in depth. topics designing your own classes attributes and behaviors writing classes in...

55
C++ Classes in Depth

Post on 21-Dec-2015

222 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

C++ Classes in Depth

Page 2: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Topics

Designing Your Own ClassesAttributes and BehaviorsWriting Classes in C++Creating and Using Objects

Page 3: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Objectives

At the completion of this topic, students should be able to:

Design classes for use in a C++ programExplain the difference between a class and an objectExplain what attributes and behaviors areExplain the terms encapsulation and data hidingCreate a program that uses a programmer designed class

Page 4: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Let’s review some concepts from CS 1400

Page 5: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Objects are used to model real-world things.You can think of an object as a rather complexvariable that contains multiple chunks of data

Page 6: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Let’s consider an object that represents a time.

Page 7: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Real world objects have attributes

An object’s attributes describe its“state of being”

What things do we normally associate with the state of a time?

seco

nds minutes

hours am/pm

Page 8: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

We hide the data from anyone outsideof the object by making it “private”

A Time object

Joe WageEarner

12356

$12.50

40

Page 9: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

The attributes of an object arestored inside the object as

data members.

An “Time” object

The hour valueis stored as an integer

The minute valueis stored as an integer

am or pm isstored as a string

3

35

pm

Page 10: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

An object also has behaviors

behaviors define how you interact with the object

What can you do with a time?

Get the hours

set the

hours

Page 11: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Behaviors are expressed as methods thatgive us controlled access to the data.

These are “public” so that we can see them.

An “Time” object

Joe WageEarner

12356

$12.50

40

getH

our ( )

setHour( )

Page 12: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Then we write statements thatsend messages to the objects

An “Time” object named joe

Joe WageEarner

12356

$12.50

40

getH

our ( )

setHour ( )

joe.getHours( );

Page 13: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

An Object’s Attributes and Behaviors Should Work Together

this is called cohesion

Page 14: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

EncapsulationTime object

getHour( )

hourminute

calling method

we should not allow codeoutside of the object to reach in and change the data directly. Instead, we call methods in theobject to do it for us.

member data is declared as private

member methods are declared as public

The terms public and private are called access modifiers

Page 15: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

A Class is a blueprint that a programuses when it creates an object.

A class reserves no space in memory

When an object is created from the classblueprint, memory is reserved to hold the

object’s attributes.

An object is known as an instance of the class.

Each object has it’s own space and data.

Page 16: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

A class is said to be an abstraction of thereal world object that we are modeling.

Classes are sometimes calledAbstract Data Types.

Page 17: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

We use a UML Class Diagram to documentthe data and methods contained in

our class.

Page 18: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Time

A UML class diagram is usedto describe a class in a very preciseway.

A class diagram is a rectangle.

At the top of the rectangle is theclass name. A line separates theclass name from the rest of thediagram.

Page 19: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Time

- hour: intFollowing the class name we writethe data members of the class. Aline separates the data membersfrom the rest of the diagram.

access modifier:+ public- private

data member name

data type

Page 20: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Time

- hour: int- minute: int

Following the data members, wewrite the member functions.

+ getHour( ): int

access modifier + public - private

method name

parameters

return type

Page 21: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

It is important that class diagrams be drawnprecisely and that they conform to the form

shown in these examples.

Page 22: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

In C++ the class definition usually goesinto a separate file called the header file.

It has a file extension of .h

mytime.h

class Time{ private: int hour; int minutes; string amOrPm public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ); void setHour( int n); void setMinutes( int n); void setAmOrPm(string a);};

Page 23: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

In C++ the class definition usually goesinto a separate file called the header file.

It has a file extension of .h

mytime.h

class Time{ private: int hour; int minutes; string amOrPm public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ); void setHour( int n); void setMinutes( int n); void setAmOrPm(string a);};

Notice that getter functions (functionsthat do not change the state of theobject) are declared as const functions.

Page 24: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Declaring Member Data

class Time{ private: int hour; int minutes; string amOrPm;

}

Member data is always “private”

Indent each line inside the block

data type

variable name

Page 25: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Declaring Member Data

We call data members of a class “Instance Data”because each instance (object) of the classwill contain its own unique copy of this data.

class Time{ private: int hour; int minutes; string amOrPm;

}

Page 26: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Declaring Member Methods

public class Time{ private: . . . public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ) const; void setHour( int n); void setMinutes( int n); void setAmOrPm(string a);

Member methods are usually public

return typefunction name

parameters

When would you make a method private?

These are calledfunction prototypes

Page 27: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

In C++ the code that implements the memberfunctions of the class goes into a related file

with the file extension .cpp

mytime.cpp

#include “mytime.h” . . .

string Time::getHour( ) const{ return hour;}

void Time::setHour( double n){ hour = n} . . .

always #includethe .h file for

this class

Class name followed by ::

Page 28: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

“Setter”Methods

void Time::setHour(int hr) { hour = hr;

}

setters neverreturn anything

they are usually named“set” plus the name of theinstance variable theywill store the value in.

setters always takea parameter

Page 29: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

“Getter”Methods

int Time::getHour( ) const { return hour;

}

getters always return something

they are usually named“get” plus the name of theinstance variable theywill return the value of.

getters take no parameters

The const keywordis required to tell thecompiler that the functiondoes not alter the object.

Page 30: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

The methods of a class

are the public services or the public interface thatthis class offers to its clients.

Clients are neither aware of nor involved in the implementationdetails of these methods. Clients care what a method does, butnot how it does it.

Page 31: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Static Data

Every instance object has its own copy of all of the instance variables in a class.

What if you want to have all objects of a class share a single instance of a variable? For example, all savingsAccount objects might have the sameinterest rate.

To do this, declare the variable as

private static double interestRate = 0.0725;

Page 32: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Static Methods

A static method can be called without creating an object of the class that it belongs to. Static methods don’t operate on data in an object unless the data itself is declared as static. When you invoke a static method you use the nameof the class instead of an object name.

Page 33: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

The this reference

Every instance object contains a variable named thisthat is a pointer to itself.

The keyword is often used when you want to explicitly name a variable as a data member of this object. For example, in the Time class we havediscussed is a method

void setHour( int hr) { hour = hr; }

Page 34: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

The this reference

Using the this reference we could write:

void setHour( int hr) { this->hour = hr; }

More to come on pointers and “this” in a few weeks.

Page 35: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Creating Objects

Page 36: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

class Time{ private: int hour; int minute; . . .

}

Class definition

Time startTime;

this statement takes the Time classdefinition and uses it to createthe object “startTime”.

When creating the object, storage is allocated for the each of the data members defined in the class.

startTimehour

minute

Page 37: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Constructors

When an object is created, the data members inside theobject need to be initialized. Otherwise, they take on theResidual values of the bits in the memory that the object occupies.

You can use a constructor to initialize data members in a classto values passed in to the constructor as parameters.

Page 38: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Constructors

Time::Time( ) { hour = 0; minutes = 0;}

No return typeis mentioned

A constructor has thesame name as the class.

You only need to write a non-parameterized constructor if youneed one, If you do not write a non-parameterized constructor, the compiler creates one for you. It takes no parameters and itsbody is empty, so it does not initialize anything.

Page 39: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Constructors

Time::Time(int hr, int min ) { hour = hr; minutes = min;}

You can also write aparameterized

constructor.

If you write a parameterized constructor, you must also write a non-parameterized one. The non-parameterizedconstructor is called the default constructor.

Page 40: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Sending Messages to Objects

Page 41: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

startTime.setHour(8);

message

objectname

. method name

parameter

startTimehour

minute

Page 42: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

startTime.setHour(8);

message

parameter

startTimehour

minute

void setHour(int hr){ hour = hr;}

This statement send the setHourmessage to the object named startTime.

As the method executes, the value ofthe parameter hr is stored in the instance variable hour.

Page 43: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

The code that creates objects and sends messages to them is typically written in main( ) in what we call adriver. This code is saved in a separate .cpp file.

driver.cpp

#include <iostream>#include “time.h”using namespace std;

int main( ){ Time newTime; . . .

myTime.setHour(3); . . .}

always #includethe .h file for any class used in main

Page 44: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Designing a Class

Page 45: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Classes model real world things, like …

* an employee * a student * a car * a rectangle * a circle * a bowling team . . .

Page 46: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

* A Rectangle

What words would you useto describe a rectangle, i.e.what are its attributes?

These become data members of the class.

it’s widthit’s heightit’s color

Page 47: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Draw a Class Diagram

Rectangle

- width: int- height: int

Page 48: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

* A Rectangle

What can I do with/to a Rectangle?

These become member functions of the class.

create onechange it’s height or widthcalculate it’s area

Page 49: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Draw a Class Diagram

Rectangle

- width: int- height: int

- color: string

+ Rectangle(:int, :int, :string)+ setHeight(:int)+ setWidth(:int)+ getArea( ): int

Page 50: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Create the .h File

class Rectangle{ private: int height; int width; string color; public: Rectangle ( ); Rectangle (int, int, string); void setWidth( int ); void setHeight( int ); int getArea( ) const;};

For brevity I have not included the function prologues

Page 51: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Idea of aRectangle

List• attributes• operations

ClassDiagram

.h File

Design Summary

Page 52: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

The following code createsa Rectangle object using anon-parameterized constructor.

Rectangle joe;

Don’t do this!

Rectangle joe( );

Page 53: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

When an object is created like this

Employee joe;

the employee object is stored on the stack. It is a local variable.

Page 54: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Passing Objects as Parameters

We always want to pass objects by reference.To keep from having side effects, pass byconstant reference. For example:

void printRectangle(const Rectangle&);

Page 55: C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

Lab #3 will give you some practicedesigning a class and writinga program in C++ to use it.