1 object-oriented programming using c++ class 27

52
1 Object-Oriented Programming Using C++ CLASS 27

Upload: sophie-kelley

Post on 27-Dec-2015

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Object-Oriented Programming Using C++ CLASS 27

1

Object-Oriented Programming

Using C++

CLASS 27

Page 2: 1 Object-Oriented Programming Using C++ CLASS 27

2

Objectives

• Create a class definition

• Use a constructor and destructor

• Differentiate between class interface and implementation

• Write a main driver to test set and get methods of a class

Page 3: 1 Object-Oriented Programming Using C++ CLASS 27

3

13.3 Introduction to the Class

• In C++, the class is the construct primarily used to create objects.

class class-name

{

declaration statements here

};

Page 4: 1 Object-Oriented Programming Using C++ CLASS 27

4

Example:

class Rectangle{ private: float Width, Length, Area; public: void SetData(float, float); void CalcArea(void); float GetWidth(void); float GetLength(void); float GetArea(void);};

Page 5: 1 Object-Oriented Programming Using C++ CLASS 27

5

Access Specifiers

• The key words private and public are access specifiers.

• private means they can only be accessed by the member functions.

• public means they can be called from statements outside the class.– Note: the default access of a class is private, but

it is still a good idea to use the private key word to explicitly declare private members. This clearly documents the access specification of the class.

Page 6: 1 Object-Oriented Programming Using C++ CLASS 27

6

13.4 Defining Member Functions

• Class member functions are defined similarly to regular functions.

void Rectangle::SetData(float W, float L)

{

Width = W;

Length = L;

}

Page 7: 1 Object-Oriented Programming Using C++ CLASS 27

7

13.5 Defining an Instance of a Class

• Class objects must be defined after the class is declared.

• Defining a class object is called the instantiation of a class.

• Rectangle Box; //Box is an instance of Rectangle

Page 8: 1 Object-Oriented Programming Using C++ CLASS 27

8

Accessing an Object’s Members

Box.CalcArea();

Page 9: 1 Object-Oriented Programming Using C++ CLASS 27

9

Pointers to Objects

Rectangle *BoxPtr;

BoxPtr = &Box;

BoxPtr->SetData(15,12);

Page 10: 1 Object-Oriented Programming Using C++ CLASS 27

10

Program 13-1 P. 786// This program demonstrates a simple

class.#include <iostream>// Rectangle class declaration.class Rectangle{

private:float width;float length;

Page 11: 1 Object-Oriented Programming Using C++ CLASS 27

11

Program 13-1public:

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

float getLength(void);float getArea(void);

};

Page 12: 1 Object-Oriented Programming Using C++ CLASS 27

12

// SetData copies the argument W to private

// member Width and// L to private member Length.void Rectangle::setWidth(float w){

width = w; } void Rectangel::setLength(float l)

{ length = l; }

Page 13: 1 Object-Oriented Programming Using C++ CLASS 27

13

// GetWidth returns the value in the private member// Width.float Rectangle::getWidth(void){

return width;}// GetLength returns the value in the private member// Length.float Rectangle::getLength(void){

return length;}// GetArea returns the value in the private member// Area.float Rectangle::getArea(void){ return width * length; }

Page 14: 1 Object-Oriented Programming Using C++ CLASS 27

14

int main() { Rectangle Box;

float rectWidth, rectLength;cout << "This program will calculate the area of a\n";cout << "rectangle. What is the width? ";cin >> rectWidth;cout << "What is the length? ";cin >> rectLengthBox.setwidth(rectWidth);Box.setLength(rectLength);cout << "Here is the rectangle's data:\n";cout << "Width: " << Box.getWidth() << endl;cout << "Length: " << Box.getLength() << endl;cout << "Area: " << Box.getArea() << endl; }

Page 15: 1 Object-Oriented Programming Using C++ CLASS 27

15

Program Output

This program will calculate the area of arectangle. What is the width? 10 [Enter]What is the length? 5 [Enter]Here is the rectangle's data:Width: 10Length: 5Area: 50

Page 16: 1 Object-Oriented Programming Using C++ CLASS 27

16

13.6 Why Have Private Members?

• In object-oriented programming, an object should protect its important data by making it private and providing a public interface to access that data.

Page 17: 1 Object-Oriented Programming Using C++ CLASS 27

17

13.7 Focus on Software Engineering: Some Design Considerations

• Usually class declarations are stored in their own header files. Member function definitions are stored in their own .CPP files.

• The #ifndef directive allows a program to be conditionally compiled. This prevents a header file from accidentally being included more than once.

Page 18: 1 Object-Oriented Programming Using C++ CLASS 27

18

Program 13-3 P. 796Contents of Rectangle.h#ifndef RECTANGLE_H#define RECTANGLE_H// Rectangle class declaration.class Rectangle{

private:float width;float length;

Page 19: 1 Object-Oriented Programming Using C++ CLASS 27

19

Program 13-3public:

bool setWidth(float); bool setLength(float); float getWidth(void);

float getLength(void);float getArea(void);

};#endif

Page 20: 1 Object-Oriented Programming Using C++ CLASS 27

20

Contents of Rectangle.CPP#include "rectang.h"

// SetWidth copies the argument w to private member // width if the argument is valid; if argument is negative // private member width is set to 0.0 and a false returned

bool Rectangle::setWidth(float w){ bool status;

if (w < 0) { width = 0.0; status = false; } else { width = w;

status = true; } return status; }

Page 21: 1 Object-Oriented Programming Using C++ CLASS 27

21

Contents of Rectangle.CPP#include "rectang.h" // Setwidth copies the argument len to private member // length if the argument is valid; if argument is negative

// private member length is set to 0.0 and a false// returned

bool Rectangle::setLength(float len){ bool status;

if (l < 0) { length = 0.0; status = false; } else { length = len;

status = true; } return status; }

Page 22: 1 Object-Oriented Programming Using C++ CLASS 27

22

Program continues

// GetWidth returns the value in the private member Width.

float Rectangle::getWidth(void){

return width;}// GetLength returns the value in the private member

Length.float Rectangle::GetLength(void){ return length;}// GetArea returns the value in the private member Area.float Rectangle::GetArea(void){ return width * length; }

Page 23: 1 Object-Oriented Programming Using C++ CLASS 27

23

Contents of the main program, PR13-3.CPP// This program demonstrates a simple class.#include <iostream>#include “rectangle.h" // contains Rectangle class

declarationusing namespace std;// Don't forget to link this program with Rectangle.cpp!int main(){ Rectangle Box;

float rectWidth, rectLength;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;

Page 24: 1 Object-Oriented Programming Using C++ CLASS 27

24

Program continues

if (!Box.setWidth(rectWidth)) cout << “invalid value for width”; else if (

if (!Box.setLength(rectLength)) cout << “invalid value for length;else

{cout << "Here rectangle's data:\n";cout << "Width: " << Box.getWidth() << endl;cout << "Length: " << Box.getLength() << endl;cout << "Area: " << Box.getArea() << endl; }

return 0; }

Page 25: 1 Object-Oriented Programming Using C++ CLASS 27

25

Performing I/O in a Class Object

• Notice that the Rectangle example has no cin or cout.

• This is so anyone who writes a program that uses the Rectangle class will not be “locked into” the way the class performs input or output.

• Unless a class is specifically designed to perform I/O, operations like user input and output are best left to the person designing the application.

Page 26: 1 Object-Oriented Programming Using C++ CLASS 27

26

Table 13-1 P. 799

• Rectangle.h Contains the declaration of the Rectangle class.

• Rectangle.cpp Contains the Rectangle class’s member function definitions.

• Pr13-3.cpp Contains functiton main

Page 27: 1 Object-Oriented Programming Using C++ CLASS 27

27

13.6 Focus on Software Engineering: Using Private Member Functions

• A private member function may only be called from a function that is a member of the same object.

Page 28: 1 Object-Oriented Programming Using C++ CLASS 27

28

13.7 Inline Member Functions

• When the body of a member function is defined inside a class declaration, it is declared inline.

Page 29: 1 Object-Oriented Programming Using C++ CLASS 27

29

P. 805// Rectangle class declaration with some functions

// written inlineclass Rectangle{ private:

float width;float length;public: bool setWidth(float); // not inlined; would be // defined in .cpp file bool setLength(float); // not inlined float getWidth() { return width(); } // inlined // would not be in .cpp float getLength() { return length(); } float getArea() { return width * length; }

Page 30: 1 Object-Oriented Programming Using C++ CLASS 27

30

13.10 Constructors

• A constructor is a member function that is automatically called when a class object is created.

• Constructors have the same name as the class.

• Constructors must be declared publicly.

• Constructors have no return type.

Page 31: 1 Object-Oriented Programming Using C++ CLASS 27

31

Program 13-5 P. 807// This program demonstrates a constructor.#include <iostream>using namespace std;class Demo{public:

Demo(void); // Constructor};

Demo::Demo(void){

cout << "Welcome to the constructor!\n";}

Page 32: 1 Object-Oriented Programming Using C++ CLASS 27

32

Program continues

int main(){

Demo DemoObj; // Declare a Demo object;cout << "This program demonstrates an object\n";cout << "with a constructor.\n";

return 0; }

Page 33: 1 Object-Oriented Programming Using C++ CLASS 27

33

Program Output

Welcome to the constructor.This program demonstrates an objectwith a constructor.

Page 34: 1 Object-Oriented Programming Using C++ CLASS 27

34

Constructor Arguments

• When a constructor does not have to accept arguments, it is called an object’s default constructor. Like regular functions, constructors may accept arguments, have default arguments, be declared inline, and be overloaded.

Page 35: 1 Object-Oriented Programming Using C++ CLASS 27

35

Program 13-7 P. 809class InventoryItem{

private:char *description;int units;

public:InventoryItem(void) { description = new char[51]; }void setDescription(char *d)

{ strcpy(description,d); } void setUnits(int u) { units = u; }

char *getDescription(void) { return description; }int getUnits(void) { return units; }

};

Page 36: 1 Object-Oriented Programming Using C++ CLASS 27

36

Program continues

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; }

Page 37: 1 Object-Oriented Programming Using C++ CLASS 27

37

Program Output

Item Description: WrenchUnits on hand: 20

Page 38: 1 Object-Oriented Programming Using C++ CLASS 27

38

13.11 Destructors• A destructor is a member function that is

automatically called when an object is destroyed.– Destructors have the same name as the class,

preceded by a tilde character (~)– In the same way that a constructor is called then

the object is created, the destructor is automatically called when the object is destroyed.

– In the same way that a constructor sets things up when an object is created, a destructor performs shutdown procedures when an object is destroyed.

Page 39: 1 Object-Oriented Programming Using C++ CLASS 27

39

Program 13-8 P. 810// This program demonstrates a constructor.#include <iostream>using namespace std; class Demo{public:

Demo(void); // Constructor~Demo(void); // Destructor

};

Demo::Demo(void){

cout << "Welcome to the constructor!\n";}

Page 40: 1 Object-Oriented Programming Using C++ CLASS 27

40

Demo::~Demo(void){

cout << "The destructor is now running.\n";}

int main(){

Demo DemoObj; // Declare a Demo object;cout << "This program demonstrates an object\n";cout << "with a constructor and destructor.\n";

return 0; }

Page 41: 1 Object-Oriented Programming Using C++ CLASS 27

41

Program Output

Welcome to the constructor!This program demonstrates an objectwith a constructor and destructor.The destructor is now running.

Page 42: 1 Object-Oriented Programming Using C++ CLASS 27

42

Program 13-9class InventoryItem{ private:

char *description;int units;

public:InventoryItem(void) { description = new

char[51]; } ~InventoryItem() { delete [] description; }

void setDescription(char *d) | { strcpy(description,d); }

void setUnits(int u) { units = u; }char *getDescription(void) { return description; }int getUnits(void) { return units; }

};

Page 43: 1 Object-Oriented Programming Using C++ CLASS 27

43

Program continues

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; }

Page 44: 1 Object-Oriented Programming Using C++ CLASS 27

44

Program Output

Item Description: WrenchUnits on hand: 20

Page 45: 1 Object-Oriented Programming Using C++ CLASS 27

45

13.12 Constructors that Accept Arguments

• Information can be passed as arguments to an object’s constructor.

Page 46: 1 Object-Oriented Programming Using C++ CLASS 27

46

Program 13-10 P. 813Contents of SALE.H#ifndef SALE_H#define SALE_H// Sale class declarationclass Sale{ private:

float TaxRate;float Total;

public:Sale(float Rate) { TaxRate = Rate; }void CalcSale(float Cost) { Total = Cost + (Cost * TaxRate) };float GetTotal(void) { return Total; }

};#endif

Page 47: 1 Object-Oriented Programming Using C++ CLASS 27

47

Contents of main program, PR13-10.CPP#include <iostream>

using namespace std;#include "sale.h"int main(){ Sale Cashier(0.06); // 6% sales tax rate

float Amnt;cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "Enter the amount of the sale: ";cin >> Amnt;Cashier.CalcSale(Amnt);cout << "The total of the sale is $";cout << Cashier.GetTotal << endl;

return 0; }

Page 48: 1 Object-Oriented Programming Using C++ CLASS 27

48

Program Output

Enter the amount of the sale: 125.00The total of the sale is $132.50

Page 49: 1 Object-Oriented Programming Using C++ CLASS 27

49

Program 13-11Contents of SALE2.H#ifndef SALE2_H#define SALE2_H // Sale class declarationclass Sale{ private:

float TaxRate; float Total;

public:Sale(float Rate = 0.05) { TaxRate = Rate; }void CalcSale(float Cost)

{ Total = Cost + (Cost * TaxRate) };float GetTotal(void) { return total; }

}; #endif

Page 50: 1 Object-Oriented Programming Using C++ CLASS 27

50

Program continues

Contents of main program, PR13-11.CPP#include <iostream>#include "sale2.h“

using namespace std;int main(){ Sale Cashier1; // Use default sales tax rate

Sale Cashier2(0.06); // Use 6% sales tax ratefloat Amnt;cout.precision(2);cout.set(ios::fixed | ios::showpoint);cout << "Enter the amount of the sale: ";cin >> Amnt;Cashier1.CalcSale(Amnt);Cashier2.CalcSale(Amnt);

Page 51: 1 Object-Oriented Programming Using C++ CLASS 27

51

Program continues

cout << "With a 0.05 sales tax rate, the total\n";cout << "of the sale is $";cout << Cashier1.GetTotal() << endl;cout << "With a 0.06 sales tax rate, the total\n";cout << "of the sale is $";cout << Cashier2.GetTotal() << endl;

return 0; }

Page 52: 1 Object-Oriented Programming Using C++ CLASS 27

52

Program Output

Enter the amount of the sale: 125.00With a 0.05 sales tax rate, the totalof the sale is $131.25With a 0.06 sales tax rate, the totalof the sale is $132.50