53
Structures and Classes Version 1.0

Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Embed Size (px)

Citation preview

Page 1: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Structures and ClassesVersion 1.0

Page 2: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Topics

StructuresClassesWriting Structures & ClassesMember FunctionsClass Diagrams

Page 3: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Objectives

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

Correctly use structures in a C++ programCorrectly use classes in a C++ programDesign and use programmer written structures & classes in a C++ programExplain the difference between a structure, class and an objectExplain what properties and behaviors areExplain the difference between the structure or class interface and thestructure or class implementationWrite member functions for a structure and classCreate accurate class diagrams using UML

Page 4: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Structures

In C++, the idea of a class has its roots in data type calledstructure. Structures were defined in the C language. Astructure is simply a way of collecting a set of differentdata types together, and treating the collection as a unit.i.e. a user defined datatype.

Page 5: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Structure Definition

struct CDAccount{ double balance; double interestRate; int term;};

the struct keyword tellsthe compiler that what followsis a structure type definition.

this is the name of the structure type. It isalso known as the structure tag. It is any validC++ identifier.

the data members of thestructure are contained in

a set of curly braces.

the structure type definition mustend with a semicolon.

Page 6: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

#include <iostream>using namespace std;

struct CDAccount{ double balance; double interestRate; int term;};

int main ( ){ CDAccount myAccount; . . .

}

The structure type definition is written outside of any function. The structure type definition must appear before it is used in the program.

Once the structure type is defined, it can be used anyplace in the program, just like any of the pre-defined data types, to create an element (object) of that data type.

Page 7: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

#include <iostream>using std::cin;using std::cout;

struct CDAccount{ double balance; double interestRate; int term;};

int main ( ){ CDAccount myAccount; . . .

}

In this case, myAccount is variable whosedata type is CDAccount. The variable (object) myAccount actually consists of three pieces of data:

myAccount

Page 8: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

#include <iostream>using std::cin;using std::cout;

struct CDAccount{ double balance; double interestRate; int term;};

int main ( ){ CDAccount myAccount; . . .

}

myAccount

these smaller pieces of data are calledmember variables. We specify themas follows:

* myAccount.balance * myAccount.interestRate * myAccount.term

myAccount.balance

myAccount.interestRate

myAccount.term

myAccount.balance

this is called the dot operator

Page 9: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

#include <iostream>using std::cin;using std::cout;

struct CDAccount{ double balance; double interestRate; int term;};

int main ( ){ CDAccount myAccount; . . .

}

myAccount

member variables are used just like any other variable …

myAccount.balance = 35.50; cout << myAccount.balance; . . .

myAccount.balance

myAccount.interestRate

myAccount.term

Page 10: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

myAccount

myAccount.balance

myAccount.interestRate

myAccount.term

yourAccount

yourAccount.balance

yourAccount.interestRate

yourAccount.term

You can create many objects (variables), using thesame structure type definition.

CDAccount yourAccount, myAccount;

Page 11: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

You can initialize a structure with an initializer list(NOTE: ALL data members MUST be public!)

CDAccount billsAccount = {35.00, .08, 12};

Page 12: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

struct Members

• Member– data/variables (properties)– functions/methods (behaviors)

struct Data //class Data{ private: int _idata; char _cdata; public: void DisplayData() { cout << _idata << “ “ << _cdata << endl; }

};

Page 13: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Writing Classes

Page 14: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Key Concept

An object often models things in the real world

Page 15: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Real world objects have properties or attributes

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

color = pink

height = 6”

width = 10”

the bank isempty!

depending upon the application, some propertiesare more important than others

Amount ofmoney in bank

Page 16: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

An object also has behaviors

behaviors define how you interact with the object

Put money in! Take money out!

Count the money in the bank

Page 17: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

An Object’s Properties and Behaviors Work Together

Put money in! Take money out!

Count the money in the bank

Amount of Moneyin the Bank

this is called cohesion

Page 18: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

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 (instantiated) from the classblueprint, memory is reserved to hold the

object’s properties.

An object is known as an instance of the class.

Each object has it’s own space for data.

Page 19: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Put money in! Take money out!

Count the money in the bank

moneyInBank

data member

member function member function

member function

Page 20: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

EncapsulationCoinBank object

howMuchMoney( )

moneyInBank

calling method

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

data is declared as private

functions are declared as public

Page 21: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Example

Page 22: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

note how this variableis declared inside the class,but outside of anyfunction.

where a variable is declareddefines its scope. In this casethe variable moneyInBankis called instance data. When an object of this class is created thevariable is created in that object.The variable exists as long as theobject exists. Each CoinBank objecthas its own copy of moneyInBank.

note that thedata is declaredas private.

this is called aaccess modifier

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

double howMuchMoney ( ); void addMoney (double);

void takeMoney (double);};

Page 23: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

double howMuchMoney ( ); void addMoney (double);

void takeMoney (double);};

declaration of a data member. Datais almost always private.

the class definition lies between theopening and closing curly braces

the keyword class tells the compilerthat this is a class definition.

the class name

the private keyword defines the declarationsthat follow to be private. Anything declared asprivate cannot be seen from outside the object.

the public keyword defines the declarationsthat follow to be public. Anything declared aspublic can be seen from outside the object.

the class definition ends in a semicolon.

Page 24: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

these are the function prototypes forthe member functions of this class.The member functions define thebehavior of the class. Notice thatmember functions are usually public.

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

double howMuchMoney ( ); void addMoney (double);

void takeMoney (double);};

Page 25: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Member Functions

• When a member function is called, the flow of control in the program transfers to the first statement in the function.

• Each statement in the function is then executed, one by one.

• When the last statement in the function is executed, the flow of control returns to the point where the function was called.

Page 26: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

double CoinBank::howMuchMoney( ){ return moneyInBank;} void CoinBank::addMoney( double dollars ){ moneyInBank = moneyInBank + dollars;}

void CoinBank::takeMoney ( double dollars ){ moneyInBank = moneyInBank - dollars;}

Writing Member Functions

return type

class name scope resolutionoperator

function name

Page 27: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Using the CoinBank Classint main( ){ // create a CoinBank object and call it myBank CoinBank myBank;

myBank.addMoney (10.00); myBank.takeMoney(2.00); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Bank contains $" << myBank.howMuchMoney( ); system(“PAUSE”); return 0;}

declare a CoinBank variable named myBank.This declaration is like any other, it createsa variable of the type named.

send messages to myBank to invokemember functions of the object.

Page 28: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

double howMuchMoney ( ); void addMoney (double);

void takeMoney (double);};

Class definitionCoinBank myBank;

myBank

moneyInBank

this statement takes the CoinBank classdefinition and uses it to createthe object myBank. When creatingthe object, storage is allocated forthe member data that is defined forobjects of this class. In this case,storage is allocated for the doublevariable moneyInBank.

Page 29: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Abstract Data Types

Programmer defined classes are known as abstract data types.We call a data type an abstract data type when the details of howdata is stored and how the operations are implemented are notvisible to programmers who use the data type.

Defining a class so that these details are not known is known as information hiding, data abstraction, or encapsulation.

Page 30: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

double howMuchMoney ( ); void addMoney (double);

void takeMoney (double);};

moneyInBank

EncapsulationData members are always private. Programmers who use this class have no idea how the data is actually declared.The developer of the class is free to change the way thatmember data is declared without affecting programs thatuse this class.

Functions outside of the class have no accessto data that is declared as private in the class,except by calling member functions of the class.

Page 31: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

int main( ){ // create a CoinBank object and call it myBank CoinBank myBank;

myBank.addMoney (10.00); myBank.takeMoney(2.00); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Bank contains $" << myBank.moneyInBank; cin.get( ); return 0;}

For Example, this statement is illegal.The compiler will return a message tellingyou that moneyInBank is not accessible.

<< myBank.howMuchMoney( );

Correct this by using a member function toget the amount of money in the bank.

Page 32: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

double howMuchMoney ( ); void addMoney (double);

void takeMoney (double);};

moneyInBank

EncapsulationWith few exceptions, functions are declared as publicso that they can be accessed from code outside of theclass. However, the details of how the function isimplemented should not be of concern to anyoneusing the class.

The function prototypes listed in the class definition give other programmers the interfaceto the class. Given these function prototypes, anda few comments about the functions, anotherprogrammer knows what each function does, whatparameters to pass to the function, and what eachreturns.

Page 33: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Accessor and Mutator Functions

Accessor functions provide a way of reading private member data.For example, the function howMuchMoney( ) is an accessor function.

Mutator functions provide a way of changing private member data.For example, the function addMoney( ) is a mutator function.

Page 34: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Classes and I/O

In general, it is a good idea to make your classes independentof the environment in which your program runs. One area wherestudents often want to build in system dependencies is doing I/O.

A good rule of thumb is to never write member functions in your classes that are not cohesive sucha as reading from stdin and writing to stdout. Such classes become dependent on the environment in which they run. It is impossible to move such a class to a different environment (for example from a DOS Console environment to a Windows environment) without making significant changes to the class.

Page 35: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Class Diagrams

During the design phase of a program, designers need a precise, standardlanguage for describing classes, and the relationships between classes.

A number of different approaches to such a modeling language weredeveloped in the late 1980’s and early 1990’s. These culminated in astandard called UML (Unified Modeling Language) in the late 1990s.

Page 36: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

CoinBank

In UML, a 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 37: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

CoinBank

- moneyInBank: doubleFollowing 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 38: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

CoinBank

- moneyInBank: double

+ CoinBank ( )+ addMoney (:double): void+ takeMoney ( :double): void+ howMuchMoney( ): double

Following the data members, wewrite the member functions.

access modifier + public - private

function name

functionparameters

return type

Page 39: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Diagram to CodeGiven a class diagram, it is relatively easy

to write down the class definition.

CoinBank

- moneyInBank: double

+ CoinBank ( )+ addMoney (:double): void+ takeMoney ( :double): void+ howMuchMoney( ): double

class CoinBank{ private: double moneyInBank; public: CoinBank ( );

void addMoney (double);

void takeMoney (double); double howMuchMoney ( );

};

Page 41: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Practice

Page 42: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Design a class that represents “Integer” objects.

What are the data members of the class?

Page 43: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Design a class that represents “Integer” objects.

Suppose we want functions to set the integer value in the object retrieve the integer value in the object retrieve the reciprocal of the value in the object

Page 44: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Create the class diagramInteger

Page 45: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Create the class definitionclass Integer{

Page 46: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Create the class implementation

Page 47: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Write a main( ) to test it#include “integer.h”#include <iostream>using namespace std;

int main ( ){

Page 48: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Design a class that represents “Student” objects.You could use an object of this class to hold thestudent information you print out at the beginningof each of your programming projects.

What are the data members of the class?

Page 49: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Design a class that represents “Student” objects.

Suppose we want functions to set the name, course, and section values in the object retrieve the name, course and section values from the object

Page 50: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Create the class diagramStudent

Page 51: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Create the class definitionclass Student{

Page 52: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Create the class implementation

Page 53: Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams

Write a main( ) to test it#include “student.h”#include <iostream>using namespace std;

int main ( ){