1 cse 2341 object oriented programming with c++ note set #5

47
1 CSE 2341 Object Oriented Programming with C++ Note Set #5

Upload: arline-gray

Post on 19-Jan-2016

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

1

CSE 2341Object Oriented Programming

with C++

Note Set #5

Page 2: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

2

Quick Look

• Introduction to the C++ class– constructors/destructors– interface/implementation– attributes/member functions– using the class in a main driver

Page 3: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

3

The Class in C++

• Objects are implemented with a class in C++.

Basic syntactical features of a class:

class className

{

//declaration statements here

};

Page 4: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

4

Example Class

class Rectangle{private:

int length, width, area;public:

void setData(int, int);void calcArea();int getLength();int getWidth();void setWidth(int);void setWidth(int);int getArea();

};

access specifiers

Page 5: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

5

Access Specifiers

• 3 different access specifiers – public, private, protected – prevent members of the class from being used

in ways in which they were not intended• Private:

– only accessible by member functions of the class

• Public:– accessible by any function

• Protected:– accessible by a derived class (to come later)

• NOTE: Default access is private but should be explicitly indicated.

Page 6: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

6

Defining a member function of a class

• Can be defined inside the class interface or externally in a separate file

void Rectangle::setData(int w, int l){ width = w; length = l;

area = width * length;}

Page 7: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

7

Defining an Instance of a Class

• class objects may only be defined after the class is declared

• Instantiation– defining a class object of a particular

type

Rectangle box; box is an instanceof Rectangle

Page 8: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

8

Accessing a public member

• given an instance of an object of type T, public members of the function are accessed using the . (dot) operator

Generally: T.publicMember();

Example: box.setData(2,3);

Page 9: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

9

Pointers to Objects

• pointers to object types are acceptable

• use the -> operator to access public members from a pointer

Rectangle box;Rectangle* boxPtr;boxPtr = &box;boxPtr -> setData(4, 5);

Page 10: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

10

Interface vs. Implementation

• Interface – the declaration of the class• Implementation – the definition of the

member functions• interface and implementation are typically

separated into different files (also separate from main driver file)

• For Rectangle Class– Interface – Rectangle.h– Implementation – Rectangle.cpp

Page 11: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

11

Rectangle.h//Declaration of class Rectangle#ifndef RECTANGLE_H#define RECTANGLE_Hclass Rectangle{public:

void setWidth(float);void setLength(float);float getWidth();float getLength();float getArea();

private:float width;float length

};#endif

Rect

an

gle

.h

Page 12: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

12

#ifndef

#ifndef RECTANGLE_H#define RECTANGLE_H // Other code here#endif

• This code ensures that the class is only defined once.• If multiple source files include Rectangle, no need to compile it multiple times.

Page 13: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

13

Rectangle.cpp

#include “Rectangle.h”//Definitions of member functions

//Copies the parameter to length data membervoid Rectangle::setLenght(float l){

length = l;}

//Copies the parameter to width data membervoid Rectangle::setWidth(float w){

width = w;}

Rect

an

gle

.cp

p

Page 14: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

14

Rectangle.cpp (continued)

//return value stored in width data memberfloat Rectangle::getWidth(){

return width;}

//return value stored in length data memberfloat Rectangle::getLength(){

return length;}

//return calculated area of the rectanglefloat Rectangle::getArea(){

return length * width;}

Rect

an

gle

.cp

p

Page 15: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

15

Using the Class in Driver

//Demonstrates use of Rectangle class#include “Rectangle.h”#include <iostream>using namespace std;int main(){

Rectangle box;float temp;cout << “This program will calculate “

<< “the area of a rectangle.” << endl;cout << “What is the width? “;cin >> temp;box.setWidth(temp);

Dri

ver.

cpp

Use “” when includinga user-defined class

Page 16: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

16

Using the Class in Driver

cout << “What is the length? “; cin >> temp box.setLength(temp);

//Display all of box’s data cout<<“Length: “<<box.getLength()<<endl; cout<<“Width: “<<box.getWidth()<<endl; cout<<“Area: “<<box.getArea()<< endl;

return 0;}

Dri

ver.

cpp

Page 17: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

17

Private Data Members – Why??

• In OOP, an object should protect its private data members so they do not get inadvertently corrupted

• A public interface to that data is provided so it does not get corrupted

Page 18: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

18

A More Robust Rectangle

• Problems with the rectangle class?

• Should width or length ever be negative?

Have the functions which modifya data member return a bool

indicating success or not

Page 19: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

19

Rectangle.h//Declaration of class Rectangle#ifndef RECTANGLE_H#define RECTANGLE_Hclass Rectangle{public:

bool setWidth(float);bool setLength(float);float getWidth();float getLength();float getArea();

private:float width;float length

};#endif

Rect

an

gle

2.h

Page 20: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

20

More Robust Rectangle Implementation

#include “Rectangle.h”//Definitions of member functions

//Copies the parameter to length data memberbool Rectangle::setLength(float l){

if (l >= 0.0){ length = l;

return true;}else{

length = 0.0;return false;

}}

Rect

an

gle

w2

.cp

p

Page 21: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

21

More Robust Rectangle Implementation (continued)

//Copies the parameter to width data membervoid Rectangle::setWidth(float w){

if (w >= 0.0){ width = w;

return true; }else{ width = 0.0;

return false; }}

//return value stored in width data memberfloat Rectangle::getWidth(){

return width;}

Rect

an

gle

w2

.cp

p

Page 22: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

22

Rectangle.cpp (continued)

//return value stored in length data memberfloat Rectangle::getLength(){

return length;}

//return calculated area of the rectanglefloat Rectangle::getArea(){

return length * width;}

Rect

an

gle

2.c

pp

Page 23: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

23

Using the Class in Driver

//Demonstrates use of Rectangle class#include “Rectangle.h”#include <iostream>using namespace std;int main(){

Rectangle box;float temp;cout << “This program will calculate “

<< “the area of a rectangle.” << endl;cout << “What is the width? “;cin >> temp;

Dri

ver2

.cp

p

Page 24: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

24

Using the Class in Driver

if(!box.setWidth(temp)){

cout << “Invalid Width – width set “ << “to 0.0!” << endl;

}cout << “What is the length? “;cin >> temp;if(!box.setLength(temp)){

cout << “Invalid Length – length set ” << “ to 0.0!” << endl;

}

Dri

ver2

.cp

p

Page 25: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

25

Using the Class in Driver

//Display all of box’s data cout<<“Length: “<<box.getLength()<<endl; cout<<“Width: “<<box.getWidth()<<endl; cout<<“Area: “<<box.getArea()<< endl;

return 0;}

Dri

ver2

.cp

p

Page 26: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

26

I/O in Classes

• Notice – No cin/cout in Rectangle• Allows flexibility to use the object

– not locked into any particular error messages, prompts, etc.

• Classes should only have I/O if specifically designed for such.– Best left to the person designing the

application

Page 27: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

27

Review of Different Files

• Rectangle.h Class Interface• Rectangle.cpp Member Function

Definitions• Driver.cpp Main driver

Page 28: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

28

More on Classes

• Class can have– private member functions– public data members

• If member function is private, can only be called by other member functions of the class or friends

• Member functions may be defined inside class declaration – called inlining

Page 29: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

29

Rectangle.h//Declaration of class Rectangle#ifndef RECTANGLE_H#define RECTANGLE_Hclass Rectangle{public:

bool setWidth(float);bool setLength(float);float getWidth() {return width;}float getLength() {return length;}float getArea()

{return length * width;}private:

float width;float length

};#endif

Rect

an

gle

3.h

Inlined member functiondefinitions will not also appear in Rectangle.cpp

Page 30: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

30

Special Member Functions

The Constructor& The Destructor

Page 31: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

31

Constructor

• A constructor– is automatically called upon object

instantiation– has the same name as the name of the

class– Must be declared as a public member

function– NO RETURN TYPE!!!

Page 32: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

32

Constructor Demo Class

#include <iostream>using namespace std;class Demo{public:

Demo();};

//Constructor defined in the .h file//Usually defined in .cpp file. Demo::Demo(){

cout << “Welcome to the Constructor!” << endl;}

Dem

o.

h

Page 33: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

33

Constructor Demo Class#include “Demo.h”#include <iostream>using namespace std;int main(){

cout << “Before Object Creation” << endl;Demo demoObj;cout << “After Object Creation” << endl;return 0;

}

dem

oD

river.

cpp

Before Object CreationWelcome to the Constructor!After Object Creation

Output:

Page 34: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

34

More on Constructors

• Default Constructor – constructor which accepts no arguments

• Constructors may– accept argument– have default arguments– be declared inline– be overloaded

Page 35: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

35

Inventory Item ClassIn

ven

tory

Item

.h class InventoryItem{private:

char* descrip;int units;

public:InventoryItem(){descrip = new char[51];}void setDescription(char* x) { strcpy(descrip, x); }void setUnits(int u) {units = u;}char* getDescription() {return descrip;}int getUnits() {return units;}

};

Page 36: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

36

Inventory Item ClassIn

ven

tory

Item

Dri

ver.

cp

p

int main(){ InventoryItem stock; stock.setDescription(“Wrench”); stock.setUnits(20);

cout << “Item Description: “ << stock.getDescription() << endl; cout << “Units on Hand: “ << stock.getUnits() << endl;

return 0;}

Output:

Item Description: WrenchUnits on Hand: 20

Page 37: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

37

Destructor

• A Destructor– is a member function– is automatically called when an object is

destroyed– has the same name as the class

preceded with a tilde (~)– performs shutdown procedures– never accept parameters– cannot be overloaded

Page 38: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

38

Destructor Demo Class#include <iostream>using namespace std;class Demo{public:

Demo();~Demo();

};

Demo::Demo(){ cout << “Welcome to the Constructor!” << endl; }

Demo::~Demo(){ cout << “Goodbye from the Destructor!” << endl;}

Dem

o2

.h

Page 39: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

39

Destructor Demo Class#include “Demo2.h”#include <iostream>using namespace std;int main(){ cout << “Before Object Creation.” << endl; Demo demoObj; cout << “After Object Creation” << endl; return 0;}

dem

oD

river.

cpp

Before Object CreationWelcome to the Constructor!After Object CreationGoodbye From the Destructor!

Output:

Page 40: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

40

Inventory Item ClassIn

ven

tory

Item

2.

h

class InventoryItem{private:

char* descrip;int units;

public:InventoryItem(){descrip = new char[51];}~InventoryItem(){delete descrip;}void setDescription(char* x) { strcpy(descrip, x); }void setUnits(int u) {units = u;}char* getDescription() {return descrip;}int getUnits() {return units;}

};

Page 41: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

41

Inventory Item ClassIn

ven

tory

Item

Dri

ver.

cp

p

int main(){ InventoryItem stock; stock.setDescription(“Wrench”); stock.setUnits(20);

cout << “Item Description: “ << stock.getDescription() << endl; cout << “Units on Hand: “ << stock.getUnits() << endl;

return 0;}

Item Description: WrenchUnits on Hand: 20

Output:

Page 42: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

42

Argument Accepting Constructor

#ifndef SALE_H#deifne SALE_Hclass Sale {private: float taxRate; float total;public: Sale(float rate) { taxRate = rate; } void calcSale(float cost) { total = cost + cost * taxRate; } float getTotal() {return total;}}; #endif

Sale

.h

Page 43: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

43

Argument Accepting Constructor

#include <iostream>using namespace std;#include “Sale.h”int main() { Sale cashier(0.06); //6% tax rate float amt; cout.setprecision(2); cout.setf(ios::fixed|ios::showpoint); cout << “Enter Sale amount: “; cin >> amt; cashier.calcSale(amt); cout << “Total is: $” << cashier.getTotal() << endl; return 0;}

Sale

Dri

ver.

cpp

Page 44: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

44

Argument Accepting Constructor

#ifndef SALE_H#deifne SALE_Hclass Sale {private: float taxRate; float total;public: Sale( float rate=0.05) { taxRate = rate; } void calcSale(float cost) { total = cost + cost * taxRate; } float getTotal() {return total;}}; #endif

Sale

2.h

Default Argument

Page 45: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

45

Argument Accepting Constructor

#include <iostream>using namespace std;#include “Sale2.h”int main() { Sale cashier(0.06); //6% tax rate Sale cashier2; //5% tax rate float amt; cout.setprecision(2); cout.setf(ios::fixed|ios::showpoint); cout << “Enter Sale amount: “; cin >> amt; cashier.calcSale(amt); cashier2.calcSale(amt);

Sale

Dri

ver2

.cp

p

Page 46: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

46

Argument Accepting Constructor

cout << “Total at 5% is: $” << cashier.getTotal() << endl; cout << “Total at 6% is: $” << cashier2.getTotal() << endl; return 0;}

Sale

Dri

ver2

.cp

p

Enter Sale amount: 125.00Total at 5% is: 131.25Total at 6% is: 132.50

output:

Page 47: 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

47

Fini

?