Beruflich Dokumente
Kultur Dokumente
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
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
7-3
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
Method
automobile can move forward and backward.
Dog can walk or run, eat food.
Class Concepts
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.
7-9
Object Example
Square
Member variables (attributes)
int side;
Member functions
void setSide(int s)
{ side = s;
}
int getSide()
{ return side; }
Square objects functions: setSide - set the size of the side of the
square, getSide - return the size of the side of the square
7-10
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
7-12
Class Example
Access
specifiers
class Square
{
private:
int side;
public:
void setSide(int s)
{side = s;}
int getSide()
{return side;}
};
7-13
7-14
7-15
public:
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-16
int main()
{
// Define 2 Circle objects
Circle circle1,
circle2;
// Call the getArea function for each circle and display the returned result
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-17
7-18
7-19
7-20
inline
functions
class Square
{
private:
int side;
public:
void setSide(int s)
{side = s;}
int getSide()
{return side;}
};
7-21
int Square::getSide()
{
return side;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-22
public:
7-23
/******************************************************************
*
Circle::setRadius
******************************************************************/
void Circle::setRadius(double r)
{ radius = r;
}
/******************************************************************
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-24
int main()
{
Circle circle1,
circle2;
circle1.setRadius(1);
system("pause");
7-25
7-26
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
class Demo
{
public:
Demo()
// Constructor
{
cout << "Now the constructor is running.\n";
}
};
int main()
7-29
Constructor 2 Examples
Inline:
class Square
{
. . .
public:
Square(int s)
{ side = s; }
. . .
};
//prototype
//in class
Square::Square(int s)
{
side = s;
}
7-30
public:
7-31
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;
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);
7-34
public:
Sale(double rate)
taxRate = rate;
7-35
int main()
{
Sale cashier1(.06);
Sale cashier2;
//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;
7-36
7-37
};
Has no
parameters
// default
// constructor
// Other member
// functions go here
7-38
Has parameter
but it has a
default value
public:
Square(int s = 1) // default
{ side = s; }
// constructor
};
// Other member
// functions go here
7-39
Invoking a Constructor
To create an object using the default
constructor, use no argument list and no ()
Square square1;
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
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;
7-43
7-44
class SimpleStat
{
private:
int largest;
int sum;
int count;
bool isNewLargest(int);
public:
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
SimpleStat();
// Default constructor
7-45
// If num is valid
{
sum += num;
count++;
// Count it
if(isNewLargest(num))
// Find out if it is
largest = num;
}
else
// num is invalid
7-46
double SimpleStat::getAverage()
{
if (count > 0)
return static_cast<double>(sum) / count;
else
return 0;
}
int main()
{
int num;
SimpleStat statHelper;
7-47
7-48
7-49
public:
void storeInfo(int p, string d, int oH, double
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
double getPrice()
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-50
int main()
{
7-51
string description;
int qty;
double price;
7-52
/********************************************************
*
showValues
********************************************************/
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
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-53
7-54
// prototype
// call
7-55
7-56
public:
parameter.
// It also illustrates how to return an object
from a function.
// Prototype
#include <iostream>
#include <iomanip>
#include <string>
{ return partNum; }
// const functions. This ensures they cannot alter
any class member data.
class InventoryItem
{
private:
int partNum;
// Part number
{ return description; }
7-57
InventoryItem createItem();
int main()
{
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-58
string description;
int qty;
double price;
7-59
/***************************************************************
*
showValues
7-60
7-61
7-62
class Rectangle
{
private:
double length;
double width;
public:
void setLength(double len)
{ length = len; }
7-63
class Carpet
{
private:
double pricePerSqYd;
Rectangle size; // size is an instance of the Rectangle class
public:
void setPricePerYd(double p)
{ pricePerSqYd = p; }
7-64
int main()
{
Carpet purchase;
double pricePerYd;
double length;
double width;
7-65
7-66
7-67
#define RECTANGLE_H
bool setLength(double);
7-68
if (len >= 0)
length = len;
else
validData = false;
return validData;
}
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-69
double Rectangle::getLength()
{
return length;
double Rectangle::getWidth()
{
return width;
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"
int main()
{
Rectangle box;
7-71
{
// 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
7-72
11-73
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
int main()
{
Example ob1(10), ob2(20);
7-78
7-79
11-79
7-80
11-80
7-81
11-81
7-82
11-82
7-83
11-83
val1
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
int main()
{
const int N_DIVISIONS = 4;
Budget divisions[N_DIVISIONS];
7-86
system("pause");
7-87
7-88
11-88
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 static member function mainOffice
//**********************************************************
Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-91
int main()
{
const int N_DIVISIONS = 4;
Budget::mainOffice(amount);
7-92
7-93