Classes: Member Functions and Implementation November 22, 2002 CSE103 - Penn State University...

Post on 04-Jan-2016

217 views 3 download

Transcript of Classes: Member Functions and Implementation November 22, 2002 CSE103 - Penn State University...

Classes:Classes: Member Functions Member Functions

and and ImplementationImplementation

November 22, 2002CSE103 - Penn State University

Prepared by Doug Hogan

2

AnnouncementsAnnouncements

Homework 5 is due Monday.Correction to lab 12 handout:

Surface area of a cylinder is 2r2 + 2rh.No class next Wednesday.

3

OverviewOverview

Review ImplementationClass interface and Functions

Review of the formConstructorsModifiersAccessors

4

Review: Library Book Review: Library Book ProblemProblem

Your ideas?member data?member functions?

We’ll work with this set of member data:string author;string title;int year; string isbn;

5

ReviewReview

Implementation of class member functions is similar to nonmember functionsFunction headers vs. function prototypes

The main difference: Member functions need to know what

class they belong to (their scope)Scope resolution operator (::)

6

Scope ResolutionScope Resolution

The class name and the scope resolution operator (::) go directly before the function namee.g. void bankAccount::withdraw(int amount)

NOT bankAccount::void withdraw(int amount)

7

Implementation ExampleImplementation Example

Implementation of the bankAccount constructor:

bankAccount::bankAccount()// POST: default bankAccount object constructed with // name == “?” and balance == 0{ name = “?”; balance = 0;}

private member data

scope resolution

name

balance

default_acct

0

“?”

8

More Implementation More Implementation ExamplesExamples

void bankAccount::deposit(int amount)// PRE: amount in dollars and amount > $0// POST: amount had been added on to balance{ balance = balance + amount;}

Exercise: Implement withdraw. void bankAccount::withdraw(int amount)

// PRE: amount in dollars and amount > $0// POST: amount had been subtracted from the balance{ balance = balance - amount;}

9

Class InterfaceClass Interface Defines the WHAT, not the HOW

General form: class className{ public: // member function declarations

private: // member data declarations};

10

ReviewReview

What are the three categories of member functions?constructors

create objects (allocate memory, set initial state)

modifierschange the state of objects

accessorsmake information about the state of the

object available outside the class

11

Continuing Bank Account…Continuing Bank Account…

Last time I asked you to…Think of one more constructor, modifier,

and accessor that would be good additions to the bankAccount class.

Your ideas??

12

ConstructorsConstructors

Goal:construct objects of the classallocate memory

Four important observations…namereturn typeoverloadingcalling

13

1. Constructors: Names1. Constructors: Names

Constructors MUST have the same name as the class itself.

That's how you'll make instances of the class (objects).

Example: bankAccount class

constructor: bankAccount(); rectangle class

constructor: rectangle();

14

2. Constructors – Return 2. Constructors – Return TypeType

They don't have a return type. It's simply omitted.

Ex: bankAccount(); NOT voidNOT double, int, etc.

15

3. Constructors - 3. Constructors - OverloadingOverloading

Constructors can be overloadedCan have several constructors

same namedifferent lists of parameters

This ability allows you to create a default constructor

no parametersinitializer constructors

parameters specifying initial state of the class

16

3. Constructors - 3. Constructors - OverloadingOverloading

Example default constructor: bankAccount();

// POST: A default bankAccount object is // created with the name set to a blank and // and the balance set to $0.00

Example initializer constructors: bankAccount(string initName, double initBalance); // PRE: initName has been assigned a value // && initBalance >= 0.00 and is in dollars // POST: A bankAccount object is created with the// name set to initName// and the balance set to initBalance

bankAccount(string initName); bankAccount(double initBalance);

17

4. Constructors – Calling 4. Constructors – Calling (Client)(Client)

Not called directly, i.e. no dot notation

Default constructor call:bankAccount myAcct; no parentheses

Initializer constructor call:bankAccount myAcct(“Homer”, $100);

18

ProblemProblem

Given the libraryBook class… string author;string title;int year; string isbn;

Define a default constructor.Define two initializer constructors.

19

ProblemProblem

Define a default constructor.libraryBook();

Define two initializer constructors. libraryBook(string initTitle, string initAuthor, string initISBN, int initYear);

libraryBook(string initTitle);

20

Another exercise…Another exercise… Given the constructors we defined

libraryBook(); libraryBook(string initTitle, string initAuthor, string initISBN, int initYear);

libraryBook(string initTitle);

Construct a default libraryBook object. libraryBook book1;

Construct a libraryBook object with the initial title Starting Out With C++. libraryBook book2(“Starting Out With C++”);

21

ModifiersModifiers

The functions that do most of the work.

Note: Objects have three characteristics: namestateset of operations

Modifiers define the set of operations.

22

ModifiersModifiers Allow the client to make changes to the

private variables. Declarations look like the ones for

nonmember functions. Often, but not always, they have a void

return type.

“Set” functions Modifiers that just "set" the value of a private

variable from a parameter without doing any calculations

23

Modifiers - ExamplesModifiers - Examples void withdraw(double amount); // PRE: amount >= 0.00 and is in dollars // POST: amount is deducted from the// balance stored for the account

A set function: void resetAccount(string newName, double newBalance); // PRE: newName has been assigned a value // && newBalance >= 0.00 and is in dollars

// POST: The account object is reset with the// name set to newName and the balance// set to newBalance

24

AccessorsAccessors Allow the client to see what values the

private variables have. Don't allow the client to make changes. Return type is that of the variable being

"accessed.“

“Get” functions Accessors that just “get" the value of a private

variable from a parameter without doing any calculations

25

AccessorsAccessors

Should be declared const They don't change the state of any

variables.  Forces the issue of not making changes

Example:double getBalance() const; // POST: FCTVAL == current balance // of this account

26

More complicated accessorsMore complicated accessors

Some calculation based on the data as long as it doesn’t change the member data e.g. balance after interest w/o actually

crediting it A data member converted to different

units e.g. Fahrenheit version of Celsius temp.

Part of a data member e.g. the cents part of a dollar amount

27

ExerciseExercise

Declare an accessor for the libraryBook type.string getTitle() const;

Write the function header for the accessor. string libraryBook::getTitle() const

28

Pre- and PostconditionsPre- and Postconditions

A few new things to notePreconditions

What must be true for the method to behave as intended

Anything about the state of the object?Should another method have been called

first?May need to look at private data members

individually

29

Pre- and PostconditionsPre- and Postconditions

PostconditionsWhat is the state of the object after this

method has been called? What is returned or displayed?

What private data members have changed? How?

30

SummarySummary Implementation

Scope resolution operator (::) and class name directly before function name

Remove semicolons Interface & functions

Constructors – create instances, allocate memory same name as class no return type can have multiple with same name not called with dot notation

Modifiers – change state of private variables, define operations

Accessors – allows client to see state of private variables Pre- and postconditions

31

Preview of What’s Next…Preview of What’s Next…

Implementation Tips for implementing each kind of function

Client end More on working with objects Test drivers

More Examples Odds and Ends from Chapter 13

For next time: work on the blue worksheet