Sei sulla pagina 1di 93

Chapter 7 & 11:

Introduction to Classes and Objects


Starting Out with C++
Early Objects
Seventh Edition
by Tony Gaddis, Judy Walters,
and Godfrey Muganda

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Topics
7.1
7.2
7.3
7.4
7.5
7.6
7.7

Object-Oriented Programming
Introduction to Classes
Introduction to Objects
Defining Member Functions
Constructors
Destructors
Private Member Functions

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-2

Topics (Continued)
7.8 Passing Objects to Functions
7.9 Object Composition
7.10 Separating Class Specification,
Implementation, and Client Code
11.1 The this Pointer and Constant
Member Functions
11.2 Static Members

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-3

7.1 Object-Oriented Programming


Procedural programming uses variables to
store data, focuses on the processes/
functions that occur in a program. Data and
functions are separate and distinct.
Object-oriented programming is based on
objects that encapsulate the data and the
functions that operate on it.

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-4

Object-Oriented Programming
Terminology
object: software entity that combines data
and functions that act on the data in a single
unit
attributes: the data items of an object, stored
in member variables
member functions (methods): procedures/
functions that act on the attributes of the class
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-5

Attributes

Understanding objects and classes


Automobile: make, model, year and purchase price.
Dog has the attributes of it names, age.

Method
automobile can move forward and backward.
Dog can walk or run, eat food.

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Understanding objects and classes


Object desk, computer, building, fish, your brother.
Every object is a member of class.
Your desk is a member of the class that includes all desks.
Your fish is a member if the class that contains all fish.

In OOP, we say that

Your desk is an instance of the Desk class


Your fish is an instance of the Fish class.
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Class Concepts

Instance data value is used to maintain information specific to


individual instances. For example, each Account object maintains its
current balance.

All
Allthree
threeAccount
Account
objects
objectspossess
possessthe
the
same
sameinstance
instancedata
data
value
valuecurrent
currentbalance.
balance.

The
Theactual
actualdollar
dollar
amounts
amountsare,
are,of
of
course,
course,different.
different.

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More Object-Oriented Programming


Terminology
data hiding: restricting access to certain
members of an object. The intent is to
allow only member functions to directly
access and modify the objects data
encapsulation: the bundling of an objects
data and procedures into a single entity

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-9

Object Example
Square
Member variables (attributes)

int side;
Member functions

void setSide(int s)
{ side = s;
}
int getSide()
{ return side; }

Square objects data item: side

Square objects functions: setSide - set the size of the side of the
square, getSide - return the size of the side of the square

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-10

7.2 Introduction to Classes


Class: a programmer-defined datatype
used to define objects
It is a pattern for creating objects
Class declaration format:
class className
{
declaration;
declaration;
};
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Notice the
required ;
7-11

Access Specifiers
Used to control access to members of the class.
Each member is declared to be either
public: can be accessed by functions
outside of the class
or
private: can only be called by or accessed
by functions that are members of
the class

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-12

Class Example

Access
specifiers

class Square
{
private:
int side;
public:
void setSide(int s)
{side = s;}
int getSide()
{return side;}
};

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-13

More on Access Specifiers


Can be listed in any order in a class
Can appear multiple times in a class
If not specified, the default is private

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-14

7.3 Introduction to Objects


An object is an instance of a class
Defined just like other variables
Square sq1, sq2;

Can access members using dot operator


sq1.setSide(5);
cout << sq1.getSide();

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-15

// This program demonstrates a simple class.


#include <iostream>
#include <cmath>
using namespace std;

// Circle class declaration


class Circle
{ private:
double radius;

public:
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-16

int main()
{
// Define 2 Circle objects
Circle circle1,
circle2;

// Call the setRadius function for each circle


circle1.setRadius(1);

// This sets circle1's radius to 1

circle2.setRadius(2.5); // This sets circle2's radius to 2.5

// Call the getArea function for each circle and display the returned result
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-17

Types of Member Functions


Acessor, get, getter function: uses but
does not modify a member variable
ex: getSide

Mutator, set, setter function: modifies a


member variable
ex: setSide

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-18

7.4 Defining Member Functions


Member functions are part of a class
declaration
Can place entire function definition inside
the class declaration
or

Can place just the prototype inside the


class declaration and write the function
definition after the class
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-19

Defining Member Functions Inside the


Class Declaration
Member functions defined inside the class
declaration are called inline functions
Only very short functions, like the one
below, should be inline functions
int getSide()
{
return side;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-20

Inline Member Function Example

inline
functions

class Square
{
private:
int side;
public:
void setSide(int s)
{side = s;}
int getSide()
{return side;}
};

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-21

Defining Member Functions After the


Class Declaration
Put a function prototype in the class declaration
public:
void setRadius(double);
double getArea();
In the function definition, precede function name
with class name and scope resolution operator (::)

int Square::getSide()
{
return side;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-22

// This program demonstrates a simple class with member functions


// defined outside the class declaration.
#include <iostream>
#include <cmath>
using namespace std;

// Circle class declaration


class Circle
{ private:
double radius;

// This is a member variable.

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

public:

7-23

// The member function implementation section follows. It contains the


// actual function definitions for the Circle class member functions.

/******************************************************************
*

Circle::setRadius

* This function copies the argument passed into the parameter to

* the private member variable radius.

******************************************************************/
void Circle::setRadius(double r)
{ radius = r;
}

/******************************************************************
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-24

int main()
{
Circle circle1,

// Define 2 Circle objects

circle2;

circle1.setRadius(1);

// This sets circle1's radius to 1

circle2.setRadius(2.5); // This sets circle2's radius to 2.5

// Get and display each circle's area


cout << "The area of circle1 is " << circle1.getArea() << endl;
cout << "The area of circle2 is " << circle2.getArea() << endl;
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

system("pause");

7-25

Conventions and a Suggestion


Conventions:
Member variables are usually private
Accessor and mutator functions are usually public
Use get in the name of accessor functions, set in
the name of mutator functions
Suggestion: calculate values to be returned in
accessor functions when possible, to minimize the
potential for stale data
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-26

Tradeoffs of Inline vs. Regular Member


Functions
When a regular function is called, control
passes to the called function
the compiler stores return address of call,
allocates memory for local variables, etc.

Code for an inline function is copied into the


program in place of the call when the program
is compiled
larger executable program, but
less function call overhead, possibly faster
execution
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-27

7.5 Constructors
A constructor is a member function that is
used to initialize data members of a class
Is called automatically when an object of the
class is created
Must be a public member function
Must be named the same as the class
Must have no return type
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-28

// This program demonstrates when a constructor executes.


#include <iostream>
using namespace std;

class Demo
{
public:
Demo()

// Constructor

{
cout << "Now the constructor is running.\n";
}
};

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

int main()

7-29

Constructor 2 Examples
Inline:
class Square
{
. . .
public:
Square(int s)
{ side = s; }
. . .
};

Declaration outside the


class:
Square(int);

//prototype
//in class

Square::Square(int s)
{
side = s;
}

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-30

// This program uses a constructor to initialize a member variable.


#include <iostream>
#include <cmath>
using namespace std;

// Circle class declaration


class Circle
{ private:
double radius;

public:

// Member function prototypes

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-31

// Circle member function implementation section


Circle::Circle()
//This is the constructor. It initializes the member variable radius to 1.
{ radius = 1;
}

void Circle::setRadius(double r)
//This function validates the radius value passed to it before assigning it to member //
// variable radius
{ if (r >= 0)
radius = r;
// else leave it set to its previous value
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-32

int main()
{
// Define a Circle object. Because the setRadius function
// is never called for it, it will keep the value set
// by the constructor.
Circle circle1;

// Define a second Circle object and set its radius to 2.5


Circle circle2;
circle2.setRadius(2.5);

// Get and display each circle's area


Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

cout << "The area of circle1 is " << circle1.getArea() << endl;

7-33

Overloading Constructors
A class can have more than 1 constructor
Overloaded constructors in a class must
have different parameter lists
Square();
Square(int);

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-34

// This program demonstrates the use of overloaded constructors.


#include <iostream>
#include <iomanip>
using namespace std;

// Sale class declaration


class Sale
{
private:
double taxRate;

public:
Sale(double rate)

// Constructor with 1 parameter

// handles taxable sales

taxRate = rate;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-35

int main()
{
Sale cashier1(.06);
Sale cashier2;

// Define a Sale object with 6% sales tax


// Define a tax-exempt Sale object

// Format the output


cout << fixed << showpoint << setprecision(2);

//Get and display the total sale price for two $24.95 sales
cout << "\nWith a 0.06 sales tax rate, the total\n";
cout << "of the $24.95 sale is $";
cout << cashier1.calcSaleTotal(24.95) << endl;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

cout << "\nOn a tax-exempt purchase, the total\n";

7-36

The Default Constructor


Constructors can have any number of
parameters, including none
A default constructor is one that takes no
arguments either due to
No parameters or
All parameters have default values

If a class has any programmer-defined


constructors, it must have a programmerdefined default constructor
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-37

Default Constructor Example


class Square
{
private:
int side;
public:
Square()
{ side = 1; }

};

Has no
parameters

// default
// constructor

// Other member
// functions go here

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-38

Another Default Constructor Example


class Square
{
private:
int side;

Has parameter
but it has a
default value

public:
Square(int s = 1) // default
{ side = s; }
// constructor

};

// Other member
// functions go here

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-39

Invoking a Constructor
To create an object using the default
constructor, use no argument list and no ()
Square square1;

To create an object using a constructor that


has parameters, include an argument list
Square square1(8);

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-40

7.6 Destructors
Public member function automatically
called when an object is destroyed
Destructor name is ~className, e.g.,
~Square
Has no return type
Takes no arguments
Only 1 destructor is allowed per class
(i.e., it cannot be overloaded)
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-41

// This program demonstrates a destructor.


#include <iostream>
using namespace std;

class Demo
{
public:
Demo();

// Constructor prototype

~Demo();

// Destructor prototype

};

Copyright
2011 Pearson Education,
Inc. Publishingfunction
as Pearson definition
Addison-Wesley
Demo::Demo()
// Constructor

7-42

int main()
{
Demo demoObj;

// Declare a Demo object;

cout << "The object now exists, but is about to be destroyed.\n";


system("pause");
return 0;
}

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-43

7.7 Private Member Functions

A private member function can only


be called by another member function of
the same class
It is used for internal processing by the
class, not for use outside of the class

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-44

// This program uses a private Boolean function to determine if


// a new value sent to it is the largest value received so far.
#include <iostream>
using namespace std;

class SimpleStat
{
private:
int largest;

// The largest number received so far

int sum;

// The sum of the numbers received

int count;

// How many numbers have been received

bool isNewLargest(int);

public:
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

SimpleStat();

// Default constructor

7-45

SimpleStat::SimpleStat() //default constructor


{
largest = sum = count = 0;
}

bool SimpleStat::addNumber(int num)


{ bool goodNum = true;
if (num >= 0)

// If num is valid

{
sum += num;

// Add it to the sum

count++;

// Count it

if(isNewLargest(num))

// Find out if it is

largest = num;

// the new largest

}
else

// num is invalid

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-46

double SimpleStat::getAverage()
{
if (count > 0)
return static_cast<double>(sum) / count;
else
return 0;
}

int main()
{
int num;
SimpleStat statHelper;

cout << "Please enter the set of non-negative integer \n";


cout << "values you want to average. Separate them with \n";
Copyright
2011 Pearson
Education,
Inc. the
Publishing
as Pearson
cout <<"spaces
and enter
-1 after
last value.
\n\n"; Addison-Wesley

7-47

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-48

7.8 Passing Objects to Functions


A class object can be passed as an
argument to a function
When passed by value, function makes a
local copy of object. Original object in
calling environment is unaffected by
actions in function
When passed by reference, function can
use set functions to modify the object.
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-49

// This program illustrates passing an object to


a function.

public:
void storeInfo(int p, string d, int oH, double

// It passes it to one function by reference and

cost); // Prototype

to another by value.
#include <iostream>

int getPartNum()

#include <iomanip>

{ return partNum; }

#include <string>
using namespace std;

string getDescription()
{ return description; }

class InventoryItem
{

int getOnHand()
private:
int partNum;

{ return onHand; }
// Part number

string description; // Item description

double getPrice()
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-50

void InventoryItem::storeInfo(int p, string d, int oH, double cost)


{ partNum = p;
description = d;
onHand = oH;
price = cost;
}

// Function prototypes for client program


void storeValues(InventoryItem&); // Receives an object by reference
void showValues (InventoryItem); // Receives an object by value

int main()
{

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-51

void storeValues(InventoryItem &item)


{
int partNum;

// Local variables to hold user input

string description;
int qty;
double price;

// Get the data from the user


cout << "Enter data for the new part number \n";
cout << "Part number: ";
cin >> partNum;
cout << "Description: ";
cin.get();

// Move past the '\n' left in the

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

// input buffer by the last input

7-52

/********************************************************
*

showValues

* This function displays the member data stored in the

* InventoryItem object passed to it by value.

********************************************************/
void showValues(InventoryItem item)
{
cout << fixed << showpoint << setprecision(2) << endl;;
cout << "Part Number : " << item.getPartNum() << endl;
cout << "Description : " << item.getDescription() << endl;
cout << "Units On Hand: " << item.getOnHand() << endl;
cout << "Price

: $" << item.getPrice() << endl;

}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-53

Notes on Passing Objects


Using a value parameter for an object can
slow down a program and waste space
Using a reference parameter speeds up
program, but allows the function to modify
data in the structure
To save space and time, while protecting
structure data that should not be changed,
use a const reference parameter
void showData(const Square &s)
// header
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-54

Returning an Object from a Function


A function can return an object
Square initSquare();
s1 = initSquare();

// prototype
// call

Function must define a object


for internal use
to use with return statement

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-55

Returning an Object Example


Square initSquare()
{
Square s;
// local object
int inputSize; //local variable
cout << "Enter the length of side: ";
cin >> inputSize;
s.setSide(inputSize);
return s;
}

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-56

// This program uses a constant reference

public:

parameter.
// It also illustrates how to return an object

void storeInfo(int p, string d, int oH, double cost);

from a function.

// Prototype

#include <iostream>
#include <iomanip>

int getPartNum() const

#include <string>

// The get functions have all been made

using namespace std;

{ return partNum; }
// const functions. This ensures they cannot alter
any class member data.

class InventoryItem
{

string getDescription() const

private:
int partNum;

// Part number

{ return description; }

string description; // Item description

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

int getOnHand() const

7-57

void InventoryItem::storeInfo(int p, string d, int oH, double cost)


{ partNum = p;
description = d;
onHand = oH;
price = cost;
}

InventoryItem createItem();

// Returns an InventoryItem object

void showValues (const InventoryItem&); // Receives a reference to an


// InventoryItem object

int main()
{
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-58

* This function stores user input data in the members of a *


* locally defined InventoryItem object, then returns it. *
************************************************************/
InventoryItem createItem()
{
InventoryItem tempItem;
int partNum;

// Local InventoryItem object


// Local variables to hold user input

string description;
int qty;
double price;

// Get the data from the user


cout << "Enter data for the new part number \n";
cout << "Part number: ";
cin >> partNum;
cout << "Description: ";
Copyrightcin.get();
2011 Pearson Education,
Inc.
Publishing
Pearson
// Move
past
the '\n'as
left
in the Addison-Wesley

7-59

/***************************************************************
*

showValues

* This function displays the member data in the InventoryItem *


* object passed to it. Because it was passed as a constant

* reference, showValues accesess the original object, not a *


* copy, but it can only call member functions declared to be *
* const. This prevents it from calling any mutator functions. *
***************************************************************/
void showValues(const InventoryItem &item)
{
cout << fixed << showpoint << setprecision(2) << endl;;
cout << "Part Number : " << item.getPartNum() << endl;
cout << "Description : " << item.getDescription() << endl;
cout << "Units On Hand: " << item.getOnHand() << endl;
cout << "Price

: $" << item.getPrice() << endl;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-60

7.9 Object Composition


Occurs when an object is a member
variable of another object.
Often used to design complex objects
whose members are simpler objects
ex. (from book): Define a rectangle class.
Then, define a carpet class and use a
rectangle object as a member of a carpet
object.
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-61

Object Composition, cont.

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-62

// This program nests one class inside another. It has a class


// with a member variable that is an instance of another class.
#include <iostream>
using namespace std;

class Rectangle
{
private:
double length;
double width;
public:
void setLength(double len)
{ length = len; }

void setWidth(double wid)


Copyright{ width
2011 Pearson
= wid; } Education, Inc. Publishing as Pearson Addison-Wesley

7-63

class Carpet
{
private:
double pricePerSqYd;
Rectangle size; // size is an instance of the Rectangle class

public:
void setPricePerYd(double p)
{ pricePerSqYd = p; }

void setDimensions(double len, double wid)


Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

{ size.setLength(len/3); // Convert feet to yards

7-64

int main()
{
Carpet purchase;

// This variable is a Carpet object

double pricePerYd;
double length;
double width;

cout << "Room length in feet: ";


cin >> length;
cout << "Room width in feet : ";
cin >> width;
cout << "Carpet price per sq. yard: ";
cin >> pricePerYd;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-65

7.10 Separating Class Specification,


Implementation, and Client Code
Separating class declaration, member
function definitions, and the program that
uses the class into separate files is
considered good design

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-66

Using Separate Files


Place class declaration in a header file that serves
as the class specification file. Name the file
classname.h (for example, Rectangle.h)
Place member function definitions in a class
implementation file. Name the file classname.cpp
(for example, Rectangle.cpp)This file should
#include the class specification file.
A main program (program11.cpp) that uses the
class must #include the class specification file
and be compiled and linked with the class
implementation file.
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-67

// File Rectangle.h -- Rectangle class specification file


#ifndef RECTANGLE_H

//if not defined

#define RECTANGLE_H

// Rectangle class declaration


class Rectangle
{
private:
double length;
double width;
public:
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

bool setLength(double);

7-68

// File Rectangle.cpp -- Rectangle class function implementation file


#include "Rectangle.h

bool Rectangle::setLength(double len)


{
bool validData = true;

if (len >= 0)
length = len;

// If the len is valid


// copy it to length

else
validData = false;

// else leave length unchanged

return validData;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-69

double Rectangle::getLength()
{
return length;

double Rectangle::getWidth()

{
return width;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-70

// Program11.cpp
// This program that uses the Rectangle class.
// The Rectangle class declaration is in file Rectangle.h.
// The Rectangle member function definitions are in Rectangle.cpp
// These files should all be combined into a project.
#include <iostream>
#include "Rectangle.h"

// Contains Rectangle class declaration

using namespace std;

int main()
{
Rectangle box;

// Declare a Rectangle object

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-71

// Call member functions to set box dimensions.


// If the function call returns false, it means the
// argument sent to it was invalid and not stored.
if (!box.setLength(boxLength))

// Store the length

cout << "Invalid box length entered.\n";


else if (!box.setWidth(boxWidth))

// Store the width

cout << "Invalid box width entered.\n";


else

// Both values were valid

{
// Call member functions to get box information to display
cout << "\nHere is the rectangle's data:\n";
cout << "Length: " << box.getLength() << endl;
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

cout << "Width : " << box.getWidth() << endl;

7-72

11.1 The this Pointer and Constant


Member Functions
this pointer:
- Implicit parameter passed to a member
function
- points to the object calling the function
const member function:
- does not modify its calling object
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

11-73

Consider the class


class Example
{ int x;
public:
Example(int a) { x = a;};
void setValue(int);
int getValue():
}
int Example::getValue()
{ return x;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-74
11-74

int main()
{ Example ob1(10), ob2(20);
cout << ob1.getvalue() << << ob2.getValue();
return 0;
}
Output: 10 20
How does getValue() know which object to use?
The compiler provides each member function of every class
with an implicit parameter that is a pointer to an object of the
class. So, the getValue() is equipped with a single parameter
of type pointer to Example. Similarly to setValue() has two
parameters: an pointer to an obj of the class Example and the
int a parameter.
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-75

// Used by ThisExample.cpp
//ThisExample.h
class Example
{
int x;
public:
Example(int a){ x = a;}
void setValue(int);
void printAddressAndValue();
};
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-76

//ThisExample.cpp
#include "ThisExample.h"
#include <iostream>
using namespace std;

//*****************************************
//set value of object

//*****************************************
void Example::setValue(int a)
{
x = a;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-77

// This program illustrates the this pointer. Program12.cpp


#include <iostream>
#include "ThisExample.h"
using namespace std;

int main()
{
Example ob1(10), ob2(20);

// Print the addresses of the two objects.


cout << "Addresses of objects are " << &ob1
<< " and " << &ob2 << endl;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-78

Using the this Pointer


setValue function rewritten in this manner
void Example::setValue(int a)
{
// this ->x = a;
// (*this).x = a;
}

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-79
11-79

Constant Member Functions


Declared with keyword const
When const follows the parameter list,
int getX()const

the function is prevented from modifying the object.


When const appears in the parameter list,
int setNum (const int num)

the function is prevented from modifying the


parameter. The parameter is read-only.

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-80
11-80

11.2 Static Members


Static member variable:
One instance of variable for the entire class
Shared by all objects of the class

Static member function:


Can be used to access static member
variables
Can be called before any class objects are
created
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-81
11-81

Static Member Variables


1) Must be declared in class with keyword
static:
class IntVal
{
public:
intVal(int val = 0)
{ value = val; valCount++ }
int getVal();
void setVal(int);
private:
int value;
static int valCount;
};
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-82
11-82

Static Member Variables


2) Must be defined outside of the class:
class IntVal
{
//In-class declaration
static int valCount;
//Other members not shown
};
//Definition outside of class
int IntVal::valCount = 0;
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-83
11-83

Static Member Variables


3) Can be accessed or modified by any
object of the class: Modifications by one
object are visible to all objects of the
class:
IntVal val1, val2;
valCount

val1

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

val2

11-84
7-84

#ifndef BUDGET_H
#define BUDGET_H

class Budget
{
private:
static double corpBudget;
double divBudget;
public:
Budget() { divBudget = 0; }
void addBudget(double b)
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-85

// This program demonstrates a static class member variable.


#include <iostream>
#include <iomanip>
#include "budget.h"

// For Budget class declaration

using namespace std;

// Definition of the static member of the Budget class.


double Budget::corpBudget = 0;

int main()
{
const int N_DIVISIONS = 4;
Budget divisions[N_DIVISIONS];

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

// Get the budget request for each division.

7-86

// Display the budget request for each division.


cout << setprecision(2);
cout << showpoint << fixed;
cout << "\nHere are the division budget requests:\n";
for (int count = 0; count < N_DIVISIONS; count++)
{
cout << "Division " << (count + 1) << "\t$ ";
cout << divisions[count].getDivBudget() << endl;
}

// Display the total budget request.


cout << "Total Budget Requests:\t$ ";
cout << divisions[0].getCorpBudget() << endl;
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

system("pause");

7-87

Static Member Functions

1)Declared with static before return type:


class IntVal
{ public:
static int getValCount()
{ return valCount; }
private:
int value;
static int valCount;
};
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-88
11-88

Static Member Functions


2) Can be called independently of class
objects, through the class name:
cout << IntVal::getValCount();

3) Because of item 2 above, the this pointer cannot


be used
4) Can be called before any objects of the
class have been created
5) Used mostly to manipulate static
member variables of the class

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

11-89

//budget2.h
#ifndef BUDGET_H
#define BUDGET_H

class Budget
{
private:
static double corpBudget;
double divBudget;
public:
Budget() { divBudget = 0; }
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-90

//budget2.cpp
#include "budget2.h"

// Definition of the static member of Budget class.


double Budget::corpBudget = 0;

//**********************************************************
// Definition of static member function mainOffice

// This function adds the main office's budget request to *


// the corpBudget variable.

//**********************************************************
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-91

// This program demonstrates a static class member function. program14.cpp


#include <iostream>
#include <iomanip>
#include "budget2.h"

// For Budget class declaration

using namespace std;

int main()
{
const int N_DIVISIONS = 4;

// Get the budget requests for each division.


cout << "Enter the main office's budget request: ";
double amount;
cin >> amount;
// Call the static member function of the Budget class.
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Budget::mainOffice(amount);

7-92

// Display the budget for each division.


cout << setprecision(2);
cout<< showpoint << fixed;
cout << "\nHere are the division budget requests:\n";
for (int count = 0; count < N_DIVISIONS; count++)
{
cout << "\tDivision " << (count + 1) << "\t$ ";
cout << divisions[count].getDivBudget() << endl;
}

// Print total budget requests.


cout << "Total Requests (including main office): $ ";
cout << Budget::getCorpBudget() << endl;

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

7-93

Potrebbero piacerti anche