Você está na página 1de 31

21.12.

2014

Encapsulation

Chapter 6

Structures
and Classes

All C++ programs are composed of the following two fundamental elements:

Program statements (code): This is the part of a program that performs actions and they are called functions.

Program data: The data is the information of the program which affected by the program functions.

Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse. Data encapsulation led to the important OOP concept of data hiding.

Data encapsulation is a mechanism of bundling the data, and the functions that use them and
data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of userdefined types, called classes. We already have studied that a class can contain private,
protected and public members. By default, all items defined in a class are private. For
example:

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Encapsulation
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double width; // width of a box
double height; // Height of a box
};

Abstract Data Types

The variables length, width, and height are private.


This means that they can be accessed only by
other members of the Box class, and not by any
other part of your program. This is one way
encapsulation is achieved.
To make parts of a class public (i.e., accessible to
other parts of your program), you must declare
them after the public keyword. All variables or
functions defined after the public specifier are
accessible by all other functions in your program.
Making one class a friend of another exposes the
implementation details and reduces encapsulation.
The ideal is to keep as many of the details of each
class hidden from all other classes as possible.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-2

6-3

"Abstract"
Programmers dont know details

Abbreviated "ADT"
Collection of data values together with set
of basic operations defined for the values

ADTs often "language-independent"


We implement ADTs in C++ with classes
C++ class "defines" the ADT

Other languages implement ADTs as well

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-4

21.12.2014

More Encapsulation

Principles of OOP
Information Hiding

Encapsulation

Details of how operations work not known to "user" of


class

Means "bringing together as one"

Declare a class get an object

Data Abstraction
Details of how data is manipulated within
ADT/class not known to user

Object is "encapsulation" of
Data values
Operations on the data (member functions)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Encapsulation
Bring together data and operations, but keep "details"
hidden
6-5

Public and Private Members

6-6

Public and Private Example


Modify previous example:

Data in class almost always designated


private in definition!

class DayOfYear
{
public:
void input();
void output();
private:
int month;
int day;
};

Upholds principles of OOP


Hide data from user
Allow manipulation only via operations
Which are member functions

Public items (usually member functions)


are "user-accessible"
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Data now private


Objects have no direct access
6-7

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-8

21.12.2014

Public and Private Example 2

Public and Private Style

Given previous example

Can mix & match public & private

Declare object:
DayOfYear today;

More typically place public first


Allows easy viewing of portions that can be
USED by programmers using the class
Private data is "hidden", so irrelevant to users

Object today can ONLY access


public members
cin >> today.month; // NOT ALLOWED!
cout << today.day; // NOT ALLOWED!
Must instead call public operations:

Outside of class definition, cannot change


(or even access) private data

today.input();
today.output();

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-9

6-10

Separate Interface
and Implementation

Accessor and Mutator Functions

User of class need not see details of how


class is implemented

Object needs to "do something" with its data


Call accessor member functions

Principle of OOP encapsulation

Allow object to read data


Also called "get member functions"
Simple retrieval of member data

User only needs "rules"


Called "interface" for the class
In C++ public member functions and
associated comments

Mutator member functions

Implementation of class hidden

Allow object to change data


Manipulated based on application

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Member function definitions elsewhere


User need not see them
6-11

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-12

21.12.2014

Structures versus Classes

Thinking Objects

Structures

Focus for programming changes

Typically all members public


No member functions

Before algorithms center stage


OOP data is focus

Algorithms still exist

Classes

They simply focus on their data


Are "made" to "fit" the data

Typically all data members private


Interface member functions public

Designing software solution

Technically, same

Define variety of objects and how they interact

Perceptionally, very different mechanisms


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-13

Summary 1

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-14

Summary 2

Structure is collection of different types

C++ class definition

Class used to combine data and functions


into single unit -> object

Should separate two key parts


Interface: what user needs

Member variables and member functions

Implementation: details of how class works

Can be public accessed outside class


Can be private accessed only in a member
functions definition

Class and structure types can be formal


parameters to functions
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-15

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

6-16

21.12.2014

Chapter 7
Constructors and
Other Tools

Learning Objectives
Constructors
Definitions
Calling

More Tools
const parameter modifier
Inline functions

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Constructors

Constructors

A class constructor is a special member


function of a class that is executed whenever
we create new objects of that class.
A constructor will have exact same name as
the class and it does not have any return type
at all, not even void. Constructors can be very
useful for setting initial values for certain
member variables.
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-18

7-19

Initialization of objects
Initialize some or all member variables
Other actions possible as well

A special kind of member function


Automatically called when object declared

Very useful tool


Key principle of OOP
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-20

21.12.2014

Constructor Definitions

Constructor Definition Example


Class definition with constructor:

Constructors defined like any


member function

class DayOfYear
{
public:
DayOfYear(int monthValue, int dayValue);
//Constructor initializes month and day
void input();
void output();

private:
int month;
int day;
}

Except:
1. Must have same name as class
2. Cannot return a value; not even void!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-21

Constructor Notes

7-22

Calling Constructors
Declare objects:
DayOfYear date1(7, 4),
date2(5, 5);

Notice name of constructor: DayOfYear


Same name as class itself!

Constructor declaration has no return-type

Objects are created here

Not even void!

Constructor is called
Values in parantheses passed as arguments
to constructor
Member variables month, day initialized:
date1.month 7 date2.month 5
date1.day 4 date2.day 5

Constructor in public section


Its called when objects are declared
If private, could never declare objects!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-23

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-24

21.12.2014

Constructor Equivalency

Constructor Code
Constructor definition is like all other
member functions:

Consider:
DayOfYear date1, date2
date1.DayOfYear(7, 4);
date2.DayOfYear(5, 5);

DayOfYear::DayOfYear(int monthValue, int dayValue)


{
month = monthValue;
day = dayValue;
}

// ILLEGAL!
// ILLEGAL!

Seemingly OK

Note same name around ::

CANNOT call constructors like other member


functions!

Clearly identifies a constructor

Note no return type


Just as in class definition
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-25

Alternative Definition

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-26

Constructor Additional Purpose

Previous definition equivalent to:

Not just initialize data


Body doesnt have to be empty

DayOfYear::DayOfYear(

int monthValue,
int dayValue)
: month(monthValue), day(dayValue)

In initializer version

Validate the data!

{}

Ensure only appropriate data is assigned to


class private member variables
Powerful OOP principle

Third line called "Initialization Section"


Body left empty
Preferable definition version
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-27

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-28

21.12.2014

Class with Constructors Example:


Display 7.1 Class with Constructors (1 of 3)

Overloaded Constructors
Can overload constructors just like
other functions
Recall: a signature consists of:
Name of function
Parameter list

Provide constructors for all possible


argument-lists
Particularly "how many"
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-29

Class with Constructors Example:


Display 7.1 Class with Constructors (2 of 3)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-30

Class with Constructors Example:


Display 7.1 Class with Constructors (3 of 3)

7-31

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-32

21.12.2014

Constructor with No Arguments

Explicit Constructor Calls

Can be confusing

Can also call constructor AGAIN


After object declared

Standard functions with no arguments:

Recall: constructor was automatically called then

Called with syntax: callMyFunction();

Can call via objects name; standard member


function call

Including empty parentheses

Object declarations with no "initializers":


DayOfYear date1;
DayOfYear date();

Convenient method of setting


member variables

// This way!
// NO!

What is this really?


Compiler sees a function declaration/prototype!
Yes! Look closely!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Method quite different from standard


member function call
7-33

Explicit Constructor Call Example

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Default Constructor

Such a call returns "anonymous object"

Defined as: constructor with no arguments

Which can then be assigned

One should always be defined

In Action:
DayOfYear holiday(7, 4);

Auto-Generated?
Yes & No
If no constructors AT ALL are defined Yes
If any constructors are defined No

Constructor called at objects declaration


Now to "re-initialize":
holiday = DayOfYear(5, 5);

If no default constructor:

Explicit constructor call


Returns new "anonymous object"
Assigned back to current object

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-34

Cannot declare: MyClass myObject;


With no initializers

7-35

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-36

21.12.2014

Class Member Variable Example:


Display 7.3 A Class Member Variable (1 of 5)

Class Type Member Variables


Class member variables can be any type
Including objects of other classes!
Type of class relationship
Powerful OOP principle

Need special notation for constructors


So they can call "back" to member
objects constructor

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-37

Class Member Variable Example:


Display 7.3 A Class Member Variable (2 of 5)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-38

Class Member Variable Example:


Display 7.3 A Class Member Variable (3 of 5)

7-39

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-40

10

21.12.2014

Class Member Variable Example:


Display 7.3 A Class Member Variable (4 of 5)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Class Member Variable Example:


Display 7.3 A Class Member Variable (5 of 5)

7-41

Parameter Passing Methods

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-42

The const Parameter Modifier adn inline fucntions

Efficiency of parameter passing

Please read the related sections of your


textbook
Section 7.2

Call-by-value
Requires copy be made Overhead

Call-by-reference
Placeholder for actual argument
Most efficient method

Negligible difference for simple types


For class types clear advantage

Call-by-reference desirable
Especially for "large" data, like class types

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-43

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-44

11

21.12.2014

Summary 1

Chapter 8

Constructors: automatic initialization of


class data

Operator
Overloading

Called when objects are declared


Constructor has same name as class

Default constructor has no parameters


Should always be defined

Class member variables


Can be objects of other classes
Require initialization-section

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-45

Learning Objectives

Operator Overloading Introduction

Basic Operator Overloading

Unary operators
As member functions

Friends and Automatic Type Conversion


Friend functions, friend classes
Constructors for automatic type conversion

References and More Overloading


<< and >>
Operators: = , [], ++, --

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-47

C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function
overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with
the same name as a previously declared declaration in the same scope,
except that both declarations have different arguments and obviously
different definition (implementation).
When you call an overloaded function or operator, the compiler
determines the most appropriate definition to use by comparing the
argument types you used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the
most appropriate overloaded function or operator is called overload
resolution.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-48

12

21.12.2014

Function overloading
#include <iostream>
using namespace std;
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}

Operator Overloading Introduction


Operators +, -, %, ==, etc.

int main(void)
{
printData pd;

Really just functions!

Simply "called" with different syntax:


x+7

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");

"+" is binary operator with x & 7 as operands


We "like" this notation as humans

Think of it as:
+(x, 7)

return 0;
}

"+" is the function name


x, 7 are the arguments
Function "+" returns "sum" of its arguments

void print(char* c) {
cout << "Printing character: " << c <<
endl;
}
};
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

7-49

8-50

Overloading Basics

Operator Overloading Perspective


Built-in operators

Overloading operators

e.g., +, -, = , %, ==, /, *
Already work for C++ built-in types
In standard "binary" notation

VERY similar to overloading functions


Operator itself is "name" of function

Example Declaration:

We can overload them!

const Money operator +(

To work with OUR types!


To add "Chair types", or "Money types"

const Money& amount1,


const Money& amount2);

Overloads + for operands of type Money


Uses constant reference parameters for efficiency
Returned value is type Money

As appropriate for our needs


In "notation" were comfortable with

Always overload with similar "actions"!


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Allows addition of "Money" objects


8-51

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-52

13

21.12.2014

Money "+" Definition:


Display 8.1 Operator Overloading

Overloaded "+"
Given previous example:

Definition of "+" operator for Money class:

Note: overloaded "+" NOT member function


Definition is "more involved" than simple "add"
Requires issues of money type addition
Must handle negative/positive values

Operator overload definitions generally


very simple
Just perform "addition" particular to "your" type

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-53

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-54

Overloaded "==" for Money:


Display 8.1 Operator Overloading

Overloaded "=="

Definition of "==" operator for Money class:

Equality operator, ==
Enables comparison of Money objects
Declaration:
bool operator ==(const Money& amount1,
const Money& amount2);
Returns bool type for true/false equality

Again, its a non-member function


(like "+" overload)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-55

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-56

14

21.12.2014

Constructors Returning Objects

Returning by const Value

Constructor a "void" function?

Consider "+" operator overload again:

We "think" that way, but no


A "special" function

const Money operator +(const Money& amount1,


const Money& amount2);

With special properties


CAN return a value!

Returns a "constant object"?


Why?

Recall return statement in "+" overload


for Money type:

Consider impact of returning "non-const"


object to see

return Money(finalDollars, finalCents);


Returns an "invocation" of Money class!
So constructor actually "returns" an object!
Called an "anonymous object"
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-57

Returning by non-const Value

8-58

What to do with Non-const Object

Consider "no const" in declaration:


Money operator +(
const Money& amount1,
const Money& amount2);

Can call member functions:


We could invoke member functions on
object returned by expression m1+m2:
(m1+m2).output(); //Legal, right?

Consider expression that calls:


m1 + m2

Not a problem: doesnt change anything

(m1+m2).input();
PROBLEM!

Where m1 & m2 are Money objects


Object returned is Money object
We can "do things" with objects!

//Legal!

//Legal, but MODIFIES!

Allows modification of "anonymous" object!


Cant allow that here!

So we define the return object as const

Like call member functions

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-59

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-60

15

21.12.2014

Overloading Unary Operators

Overload "-" for Money


Overloaded "-" function declaration

C++ has unary operators:

Placed outside class definition:


const Money operator (const Money& amount);
Notice: only one argument

Defined as taking one operand


e.g., - (negative)
x = -y;

// Sets x equal to negative of y

Since only 1 operand (unary)

Other unary operators:

"-" operator is overloaded twice!

++, --

For two operands/arguments (binary)


For one operand/argument (unary)
Definitions must exist for both

Unary operators can also be overloaded

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-61

Overloaded "-" Definition

8-62

Overloaded "-" Usage


Consider:
Money amount1(10),
amount2(6),
amount3;
amount3 = amount1 amount2;

Overloaded "-" function definition:


const Money operator (const Money& amount)
{
return Money(-amount.getDollars(),
-amount.getCents());
}

Calls binary "-" overload

amount3.output();
//Displays $4.00
amount3 = -amount1;

Applies "-" unary operator to built-in type


Operation is "known" for built-in types

Calls unary "-" overload

amount3.output()

Returns anonymous object again


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-63

//Displays -$10.00

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-64

16

21.12.2014

Member Operator in Action

Overloading as Member Functions


Previous examples: standalone functions

Money cost(1, 50), tax(0, 15), total;


total = cost + tax;

Defined outside a class

If "+" overloaded as member operator:

Can overload as "member operator"

Variable/object cost is calling object


Object tax is single argument

Considered "member function" like others

Think of as: total = cost.+(tax);

When operator is member function:


Only ONE parameter, not two!
Calling object serves as 1st parameter

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Declaration of "+" in class definition:


const Money operator +(const Money& amount);
Notice only ONE argument

8-65

8-66

Overloading Operators:
Which Method?

const Functions

Object-Oriented-Programming

When to make function const?


Constant functions not allowed to alter class
member data
Constant objects can ONLY call constant
member functions

Principles suggest member operators


Many agree, to maintain "spirit" of OOP

Member operators more efficient

Good style dictates:

No need to call accessor &


mutator functions

Any member function that will NOT modify data


should be made const

At least one significant disadvantage

Use keyword const after function


declaration and heading
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

(Later in chapter)
8-67

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-68

17

21.12.2014

Other Overloads

Overloading Function Application ()


Function call operator, ( )

&&, ||, and comma operator

Must be overloaded as member function


Allows use of class object like a function
Can overload for all possible numbers
of arguments

Predefined versions work for bool types


Recall: use "short-circuit evaluation"
When overloaded no longer uses
short-circuit
Uses "complete evaluation" instead
Contrary to expectations

Example:
Aclass anObject;
anObject(42);

Generally should not overload


these operators

If ( ) overloaded calls overload


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-69

Summary 1

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-70

Chapter 10

C++ built-in operators can be overloaded

Pointers and
Dynamic Arrays

To work with objects of your class

Operators are really just functions


Operators can be overloaded as
member functions
1st operand is calling object

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

8-71

18

21.12.2014

Learning Objectives

Pointer Introduction

Pointers

Pointer definition:

Pointer variables
Memory management

Memory address of a variable

Recall: memory divided

Dynamic Arrays

Numbered memory locations


Addresses used as name for variable

Creating and using


Pointer arithmetic

Youve used pointers already!

Classes, Pointers, Dynamic Arrays


The this pointer
Destructors, copy constructors

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Call-by-reference parameters
Address of actual argument was passed
10-73

Pointer Variables

10-74

Declaring Pointer Variables

Pointers are "typed"

Pointers declared like other types

Can store pointer in variable


Not int, double, etc.

Add "*" before variable name


Produces "pointer to" that type

Instead: A POINTER to int, double, etc.!

"*" must be before each variable

Example:
double *p;

int *p1, *p2, v1, v2;

p is declared a "pointer to double" variable


Can hold pointers to variables of type double

p1, p2 hold pointers to int variables


v1, v2 are ordinary int variables

Not other types! (unless typecast, but could be dangerous)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-75

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-76

19

21.12.2014

Addresses and Numbers

Pointing

Pointer is an address

Terminology, view
Talk of "pointing", not "addresses"
Pointer variable "points to" ordinary variable
Leave "address" talk out

Address is an integer
Pointer is NOT an integer!
Not crazy abstraction!

Makes visualization clearer

C++ forces pointers be used as


addresses

"See" memory references


Arrows

Cannot be used as numbers


Even though it "is a" number
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-77

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Pointing to

Pointing to

int *p1, *p2, v1, v2;


p1 = &v1;

Recall:
int *p1, *p2, v1, v2;
p1 = &v1;

Sets pointer variable p1 to "point to" int


variable v1

Two ways to refer to v1 now:


Variable v1 itself:
cout << v1;
Via pointer p1:
cout *p1;

Operator, &
Determines "address of" variable

Read like:

Dereference operator, *

"p1 equals address of v1"


Or "p1 points to v1"

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-78

Pointer variable "derereferenced"


Means: "Get data that p1 points to"
10-79

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-80

20

21.12.2014

"Pointing to" Example

& Operator

Consider:

The "address of" operator

v1 = 0;
p1 = &v1;
*p1 = 42;
cout << v1 << endl;
cout << *p1 << endl;

Also used to specify call-by-reference


parameter
No coincidence!
Recall: call-by-reference parameters pass
"address of" the actual argument

Produces output:
42
42

Operators two uses are closely related

p1 and v1 refer to same variable


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-81

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-82

Pointer Assignments Graphic:


Display 10.1 Uses of the Assignment Operator with
Pointer Variables

Pointer Assignments
Pointer variables can be "assigned":
int *p1, *p2;
p2 = p1;
Assigns one pointer to another
"Make p2 point to where p1 points"

Do not confuse with:


*p1 = *p2;
Assigns "value pointed to" by p1, to "value
pointed to" by p2

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-83

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-84

21

21.12.2014

Basic Pointer Manipulations Example:


Display 10.2 Basic Pointer
Manipulations (1 of 2)

The new Operator


Since pointers can refer to variables
No "real" need to have a standard identifier

Can dynamically allocate variables


Operator new creates variables
No identifiers to refer to them
Just a pointer!

p1 = new int;
Creates new "nameless" variable, and
assigns p1 to "point to" it
Can access with *p1
Use just like ordinary variable
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-85

Basic Pointer Manipulations Example:


Display 10.2 Basic Pointer
Manipulations (2 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-86

Basic Pointer
Manipulations
Graphic:
Display 10.3
Explanation of
Display 10.2

10-87

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-88

22

21.12.2014

More on new Operator

Pointers and Functions

Creates new dynamic variable

Pointers are full-fledged types


Can be used just like other types

Returns pointer to the new variable

Can be function parameters

If type is class type:


Constructor is called for new object
Can invoke different constructor with
initializer arguments:

Can be returned from functions


Example:
int* findOtherPointer(int* p);

MyClass *mcPtr;
mcPtr = new MyClass(32.0, 17);

This function declaration:

Can still initialize non-class types:


int *n;
n = new int(17);

Has "pointer to an int" parameter


Returns "pointer to an int" variable

//Initializes *n to 17

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-89

Memory Management

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-90

Checking new Success


Older compilers:

Heap
Also called "freestore"
Reserved for dynamically-allocated variables
All new dynamic variables consume memory
in freestore

Test if null returned by call to new:


int *p;
p = new int;
if (p == NULL)
{
cout << "Error: Insufficient memory.\n";
exit(1);
}

If too many could use all freestore memory

Future "new" operations will fail if freestore


is "full"

If new succeeded, program continues


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-91

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-92

23

21.12.2014

new Success New Compiler

Freestore Size
Varies with implementations

Newer compilers:
If new operation fails:

Typically large

Program terminates automatically


Produces error message

Most programs wont use all memory

Memory management

Still good practice to use NULL check

Still good practice


Solid software engineering principle
Memory IS finite
Regardless of how much there is!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-93

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

delete Operator

Dangling Pointers

De-allocate dynamic memory

delete p;
Destroys dynamic memory
But p still points there!

When no longer needed


Returns memory to freestore

Called "dangling pointer"

Example:

If p is then dereferenced ( *p )

int *p;
p = new int(5);
//Some processing
delete p;

Unpredicatable results!
Often disastrous!

Avoid dangling pointers

De-allocates dynamic memory "pointed to by


pointer p"

Assign pointer to NULL after delete:


delete p;
p = NULL;

Literally "destroys" memory


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-94

10-95

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-96

24

21.12.2014

Dynamic and Automatic Variables


Dynamic variables

Can "name" pointer types

Created with new operator


Created and destroyed while program runs

To be able to declare pointers like other


variables

Local variables

Eliminate need for "*" in pointer declaration

Declared within function definition


Not dynamic

typedef int* IntPtr;


Defines a "new type" alias
Consider these declarations:
IntPtr p;
int *p;

Created when function is called


Destroyed when function call completes

Often called "automatic" variables


Properties controlled for you

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Define Pointer Types

The two are equivalent

10-97

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-98

Call-by-value Pointers Example:


Display 10.4 A Call-by-Value Pointer Parameter (1
of 2)

Pitfall: Call-by-value Pointers


Behavior subtle and troublesome
If function changes pointer parameter
itself only change is to local copy

Best illustrated with example

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-99

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-100

25

21.12.2014

Call-by-value Pointers Example:


Display 10.4 A Call-by-Value Pointer Parameter (2
of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-101

Call-by-value Pointers Graphic:


Display 10.5 The Function Call sneaky(p);

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Dynamic Arrays

Array Variables
Recall: arrays stored in memory
addresses, sequentially

Array variables
Really pointer variables!

Array variable "refers to" first indexed variable


So array variable is a kind of pointer variable!

Standard array
Fixed size

Example:
int a[10];
int * p;

Dynamic array
Size not specified at programming time
Determined while program running
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-102

a and p are both pointer variables!

10-103

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-104

26

21.12.2014

Array Variables Pointers

Array Variables Pointers

Recall previous example:

Array variable
int a[10];

int a[10];
typedef int* IntPtr;
IntPtr p;

MORE than a pointer variable


"const int *" type
Array was allocated in memory already
Variable a MUST point therealways!

a and p are pointer variables


Can perform assignments:
p = a; // Legal.

Cannot be changed!

p now points where a points

In contrast to ordinary pointers

To first indexed variable of array a

Which can (& typically do) change

a = p; // ILLEGAL!
Array pointer is CONSTANT pointer!
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-105

Dynamic Arrays

10-106

Creating Dynamic Arrays

Array limitations

Very simple!

Must specify size first


May not know until program runs!

Use new operator


Dynamically allocate with pointer variable
Treat like standard arrays

Must "estimate" maximum size needed

Example:

Sometimes OK, sometimes not


"Wastes" memory

typedef double * DoublePtr;


DoublePtr d;
d = new double[10]; //Size in brackets
Creates dynamically allocated array variable d,
with ten elements, base type double

Dynamic arrays
Can grow and shrink as needed
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-107

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-108

27

21.12.2014

Deleting Dynamic Arrays

Function that Returns an Array

Allocated dynamically at run-time

Array type NOT allowed as return-type


of function

So should be destroyed at run-time

Simple again. Recall Example:

Example:
int [] someFunction(); // ILLEGAL!

d = new double[10];
//Processing
delete [] d;
De-allocates all memory for dynamic array
Brackets indicate "array" is there
Recall: d still points there!

Instead return pointer to array base type:


int* someFunction(); // LEGAL!

Should set d = NULL;

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-109

Pointer Arithmetic

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-110

Alternative Array Manipulation


Use pointer arithmetic!

Can perform arithmetic on pointers


"Address" arithmetic

"Step thru" array without indexing:


for (int i = 0; i < arraySize; i++)
cout << *(d + I) << " " ;

Example:
typedef double* DoublePtr;
DoublePtr d;
d = new double[10];
d contains address of d[0]
d + 1 evaluates to address of d[1]
d + 2 evaluates to address of d[2]

Equivalent to:
for (int i = 0; i < arraySize; i++)
cout << d[I] << " " ;

Only addition/subtraction on pointers


No multiplication, division

Equates to "address" at these locations

Can use ++ and -- on pointers


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-111

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-112

28

21.12.2014

Multidimensional Dynamic Arrays

The -> operator

Yes we can!

Shorthand notation

Recall: "arrays of arrays"

Combines dereference operator, *, and


dot operator

Type definitions help "see it":


typedef int* IntArrayPtr;
IntArrayPtr *m = new IntArrayPtr[3];
Creates array of three pointers
Make each allocate array of 4 ints

Specifies member of class "pointed to"


by given pointer
Example:
MyClass *p;
p = new MyClass;
p->grade = "A"; Equivalent to:
(*p).grade = "A";

for (int i = 0; i < 3; i++)


m[i] = new int[4];
Results in three-by-four dynamic array!
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Back to Classes

10-113

The this Pointer

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-114

Overloading Assignment Operator

Member function definitions might need to refer


to calling object
Use predefined this pointer
Automatically points to calling object:
Class Simple
{
public:
void showStuff() const;
private:
int stuff;
};

Assignment operator returns reference


So assignment "chains" are possible
e.g., a = b = c;
Sets a and b equal to c

Operator must return "same type" as its


left-hand side
To allow chains to work
The this pointer will help with this!

Two ways for member functions to access:


cout << stuff;
cout << this->stuff;
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-115

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-116

29

21.12.2014

Overloaded = Operator Definition

Overloading Assignment Operator

Uses string Class example:

Recall: Assignment operator must be


member of the class

StringClass& StringClass::operator=(const StringClass& rtSide)


{
if (this == &rtSide)
// if right side same as left side
return *this;
else
{
capacity = rtSide.length;
length
length = rtSide.length;
delete [] a;
a = new char[capacity];
for (int I = 0; I < length; I++)
a[I] = rtSide.a[I];
return *this;
}
}

It has one parameter


Left-operand is calling object
s1 = s2;
Think of like: s1.=(s2);

s1 = s2 = s3;
Requires (s1 = s2) = s3;
So (s1 = s2) must return object of s1"s type
And pass to " = s3";

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-117

Shallow and Deep Copies

10-118

Destructor Need
Dynamically-allocated variables

Shallow copy
Assignment copies only member variable
contents over
Default assignment and copy constructors

Do not go away until "deleted"

If pointers are only private member data


They dynamically allocate "real" data

Deep copy

In constructor

Pointers, dynamic memory involved


Must dereference pointer variables to
"get to" data for copying
Write your own assignment overload and
copy constructor in this case!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Must have means to "deallocate" when


object is destroyed

Answer: destructor!
10-119

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-120

30

21.12.2014

Destructors

Copy Constructors

Opposite of constructor

Defined like constructor, just add ~

10-121

Copy constructor creates it

Default copy constructor

Class object declared and initialized to other object


When function returns class type object
When argument of class type is "plugged in"
as actual argument to call-by-value parameter

Requires "temporary copy" of object

MyClass::~MyClass()
{
//Perform delete clean-up duties
}

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Automatically called when:


1.
2.
3.

Automatically called when object is out-of-scope


Default version only removes ordinary
variables, not dynamic variables

Like default "=", performs member-wise copy

Pointers write own copy constructor!


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

Summary 1

Summary 2
Class destructor

Pointer is memory address

Special member function


Automatically destroys objects

Provides indirect reference to variable

Dynamic variables

Copy constructor

Created and destroyed while program runs

Single argument member function


Called automatically when temp copy needed

Freestore
Memory storage for dynamic variables

Assignment operator
Must be overloaded as member function
Returns reference for chaining

Dynamically allocated arrays


Size determined as program runs
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-122

10-123

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

10-124

31

Você também pode gostar