Sunteți pe pagina 1din 90

1

Computer Programming
5. Basic Object Oriented Programming

What is an Object?
The real world is composed of different kinds of
objects: buildings, men, women, dogs, cars, etc.
Each object has its own states and behaviors.
Behaviors
Color = Red
Brand = Ferrari
Speed = 200 mph
Gear = 4

Changing
Gear

Steering

States
Variables and functions

Accelerating

Braking

Computer Programming
5. Basic Object Oriented Programming

What is a Software Object?


Software designers use the same idea to ease
programmers to develop their software
Software is also composed of different kind of
software objects
Each software object also has its own states and
behaviors.
Method
(Behavior)
Press( )

Button

Variables (States)
Color = Grey
Size = 2cm x 2cm
Shape = Rectangular
(protruded)

Computer Programming
5. Basic Object Oriented Programming

Encapsulation

Hiding information within an objects nucleus


Provide a public interface for interacting with it
Advantages to software developers
Modularity: An object can be easily passed around in the
system (Otherwise, you need to think about how many
files you need to bundle together to pass to your
friends)
Library
Reusability
Information hiding: Users need not go into details of the
object before using the object (E.g., you dont need to
know the circuit of a TV set if you want to watch TV)
Safety: Users of the object may not directly access the
internal state of the object. This reduces the possibility
of erroneous situations.

Computer Programming
5. Basic Object Oriented Programming

What is a Class?
A Class is a blueprint or prototype that defines
the variables and methods common to all objects
of a certain kind
Every object of a Class is an instance of that class
Benefit - Reusability
This arrangement saves effort in developing a number of
objects of the same kind.
Usually objects of a class
are used many times in
an application
Objects of class button

Computer Programming
5. Basic Object Oriented Programming

The Button Class


Variables
Color (e.g. Grey)
Size (e.g. 2cm x 2cm)
Press( ) Shape (e.g. Rectangular)
(protruded)

Method

Instantiation
Instance of
Button Class

Instantiation
Instance of
Button Class

Computer Programming
5. Basic Object Oriented Programming

Many Different Objects


bill
from a Single Class
Attributes:

Age = 47
Height = 177 cm
Weight = 68 kg
Methods:
Move

Person
Class

Attributes:
Age
Height
Weight
Methods:
Move

scott
Instances

Attributes:
Age = 52
Height = 182 cm
Weight = 75kg
Methods:
Move

steve
Attributes:
Age = 50
Height = 180 cm
Weight = 71 kg
Methods:
Move

larry
Attributes:
Age = 54
Height = 179 cm
Weight = 67 kg
Methods:
Move

Computer Programming
5. Basic Object Oriented Programming

Classes are implementations of Data Types


z

A class is a programmer-defined data type and objects


are variables of that type

z
z
z

Just like in int x;, x is a variable of type int

Class: in some sense, a data type that defines both data


and functions
When a data type has been created, programmers can
use it without knowing how it is implemented internally
Example: a date object might include operations for various
display formats, comparing two dates, extracting the month,
day, and year numbers, etc.
A class generally contains private data and public operations
(called member functions)

Computer Programming
5. Basic Object Oriented Programming

Declaring Classes in C++

To declare a class, use the class keyword as follows


class Cat
{
unsigned int
itsAge;
// Member variable
unsigned int
itsWeight;// Member variable
void Meow();
// Member function
}; Definition of Meow() should follow somewhere

Declaring this class does NOT allocate memory for a Cat


Only tell the compiler what a Cat is, how big a Cat is (by
member variables, e.g. itsAge, itsWeight), what a Cat
would do (by member functions, e.g. Meow() )
Declaration of classes should be placed in the header file
and included into your program. #include

Computer Programming
5. Basic Object Oriented Programming

Declaring an Object of a Class


When a class is defined, we can further define the objects of
that class:
Cat Frisky;

// define one of the Cats call Frisky

It states that we are going to handle a Cat called Frisky


It is similar to declaring a number of the type integer
int xyz;

// define one of the integers call xyz

Obviously, if one declares two cats as follows


Cat Frisky, Felix;

// define two Cats

Frisky is never the same as Felix, although they both


belong to the class Cat, i.e. they are cats.

10

Computer Programming
5. Basic Object Oriented Programming

Variable and
methods
When an object is defined, we can access the members of
that object based on its class definition

Accessing Class Members

For example, if we want to know the weight of Frisky:


unsigned int weight = Frisky.itsWeight;
// Get the weight of Frisky

The operator . allows us to access the members of the


object
Similarly, if we want to know the age of Frisky:
unsigned int age = Frisky.itsAge;
// Get the age of Frisky

If we want to ask Frisky to meow:


Frisky.Meow();

// Ask Frisky to execute meow()

11

Computer Programming
5. Basic Object Oriented Programming

Accessing Class Members


Never access directly to class
Cat.itsAge = 5;

// Dont do that! Cat is class

It is because Cat is only a template of all cats. A different


cat may have a different age
If we want to assign the age of Frisky, we write:
Frisky.itsAge = 5;

// Set the age of Frisky to 5

Also, if the class doesnt define a member, you cant use it


Frisky.bark();

// Frisky has no bark() defined

Frisky.itsColor = 5;

// Also error, because the class


//

Cat does not have itsColor

12

Computer Programming
5. Basic Object Oriented Programming

Private Versus Public


Members can be divided into public members or private
members
Private members of a class are those members that can
only be accessed by methods of that class
By default, all members are private
Public members of a class are those members that can be
accessed by other class objects and functions
This mechanism provides the privacy or security to the
information of a class that requires protection.
Typically, access private members by public methods.

13

Computer Programming
5. Basic Object Oriented Programming

Private Versus Public


#include <iostream> // for cout
using namespace std;
class Cat
// declare the class
{
int itsAge;
An
Anerror
errorisisgenerated
generatedsince
sinceby
by
int itsWeight;
default
};
defaultitsWeight
itsWeightand
anditsAge
itsAge

are
areprivate.
private.They
Theycannot
cannotbe
be

int main()
accessed
accessedeven
evenby
bymain()
main()
{
Cat Frisky;
Frisky.itsAge = 5; // assign to the member variable
cout << "Frisky is a cat who is ";
cout << Frisky.itsAge << " years old.\n";
return 0;
}

14

Computer Programming
5. Basic Object Oriented Programming

Private Versus Public


#include <iostream> // for cout
using namespace std;
class Cat
// declare the class
{
public:
int itsAge;
Now
NowitsWeight
itsWeightand
anditsAge
itsAge
int itsWeight;
are
};
arepublic
publicmembers.
members.They
Theycan
can

be
beaccessed
accessedby
bymain()
main()

int main()
{
Cat Frisky;
Frisky.itsAge = 5; // assign to the member variable
cout << "Frisky is a cat who is ";
cout << Frisky.itsAge << " years old.\n";
return 0;
}

15

Computer Programming
5. Basic Object Oriented Programming

How Private Variables are used?


#include <iostream> // for cout
using namespace std;
class Cat
// declare the class Cat
{
public: void SetAge (int age);
Public
PublicRead/write
int GetAge();
Accessor
Accessor
void SetWeight (int weight);
Methods
int GetWeight();
Methods
private: int itsAge;
Private
Privatemember
member
int itsWeight;
variables
};
variables
int Cat::GetAge()
{
return itsAge;
Accessor
}
Accessormethods
methodsprovide
provide
void Cat::SetAge(int age)
access
accessto
toprivate
privatemembers
members
{
itsAge = age;
since
they
are
in
the
since they are in thesame
sameclass
class
}

16

Computer Programming
5. Basic Object Oriented Programming

Scope Resolution Operator ( :: )


z

C++ programs typically use several class types

different classes can have member functions with the same


identifier, like Write( )

member selection operator is used to determine the class whose


member function Write( ) is invoked
currentTime .Write( ) ;
numberZ .Write( ) ;

// class TimeType
// class ComplexNumberType

in the implementation file, the scope resolution operator is used in


the heading before the function members name to specify its
class
void TimeType :: Write ( )
{
}

. . .

17

Computer Programming
5. Basic Object Oriented Programming

Implementing Class Methods


Member functions declared in a class are only prototypes
of these functions
Actual implementation (the operations performed by the
function) should be separately described.
#include <iostream> // for cout
using namespace std;
class Cat
// declare the class Cat
{
public:
To
Toindicate
indicateGetAge()
GetAge()isis
int GetAge();
aafunction
functionof
ofclass
classCat
Cat
private: int itsAge;
};
int Cat::GetAge()
{
return itsAge;
}

Thats
Thatsthe
the
implementation
implementation

18

Computer Programming
5. Basic Object Oriented Programming

Two Separate Files used


// SPECIFICATION FILE
( timetype .h )
// Specifies the data and function members.
class TimeType
{

public:
. . .

private:
. . .
};

// IMPLEMENTATION FILE
( timetype.cpp )
// Implements the TimeType member functions.
. . .

Publicly known
Only the developer
knows

19

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.2a
Based on the program in page 15, write a program that will
first print the age and weight of a cat called Felix, and then
it asks the user to input the age and weight of that cat.
To do that, you need to do the following things:
a. Complete the implementation of the member functions
GetWeight() and SetWeight().
Age and weight
b. Add the main() function that prints the current status of
a cat Felix, then ask for users input to modify the status.
c. Build the result program and note the result.
d. Before you ask the user to input the age and weight, what
are their initial values? Are they the ones you expect?

20

Computer Programming
5. Basic Object Oriented Programming

Constructors and Destructors


How do we initialize an object?
By means of the constructor of the class
Every class should have a constructor
User can define its own constructor for the class
Otherwise, the compiler will make one for the user
although it does nothing
Constructor is a function of which the compiler will call if
an object of this class is constructed (created) In memory
Besides constructor, every class has also a destructor that
will be called when the object of that class is destructed
(removed).

21

Computer Programming
5. Basic Object Oriented Programming

Class Constructors
z

a class constructor is a member function whose purpose


is to initialize the private data members of a class object

the name of a constructor is always the name of the


class, and there is no return type for the constructor

a class may have several constructors with different


parameter lists. A constructor with no parameters is the
default constructor

a constructor is implicitly invoked when a class object is


declared--if there are parameters, their values are listed
in parentheses in the declaration

22

Computer Programming
5. Basic Object Oriented Programming

class Cat
AAtypical
typicalClass
Classdefinition
definitionwith
withuseruser{
defined
definedconstructor
constructorand
anddestructor
destructor
public:
Cat(int initialAge);
// Constructor of Cat
~Cat();
// Destructor of Cat
int GetAge();
Implementation
Implementationof
of
void SetAge(int Age);
constructor
void Meow(); //public function
constructor
When
any
private:
When anyobject
objectof
ofthe
theclass
class
Cat
is
constructed,
int itsAge;
Cat is constructed,this
this
function
};
functionisiscalled
calledand
andin
in
effect
it
will
set
itsAge
Cat::Cat (int initialAge)
effect it will set itsAgeto
to
{ itsAge = initialAge;
the
parameter
passed
the parameter passed
}
Implementation
Cat::~Cat()
Implementationof
ofdestructor
destructor
When
any
object
of
the
{
When any object of theclass
classCat
Catisis
}
destructed,
destructed,this
thisfunction
functionisiscalled
calledwhich
whichin
in
void Cat::Meow() {}
effect
does
nothing
effect does nothing

23

Computer Programming
5. Basic Object Oriented Programming

Constructors and Destructors


A possible main() function for the class Cat above is as
follows:
AACat
CatFrisky
Friskyisisconstructed
constructedhere
here

// some lines of p.22


The
Theconstructor
constructorisiscalled
calledand
andthe
theparameter
parameter55
//
isispassed
passedto
tothe
theconstructor
constructorand
andin
inturn
turn
int main()
initializes
the
private
member
variable
initializes the private member variable
{
Cat Frisky(5);
itsAge
itsAgeto
to55
Frisky.Meow();
cout << "Frisky is a cat who is ";
cout << Frisky.GetAge() << " years old.\n";
Frisky.Meow(); //Meow() does nothing here
Frisky.SetAge(7);
cout << "Now Frisky is ";
cout << Frisky.GetAge() << " years old.\n";
Frisky.Meow();
return 0;
}

24

Computer Programming
5. Basic Object Oriented Programming

Destructor
z
z
z
z

Member function automatically called when object


goes out of scope
Name of destructor function required to be class
name preceded by tilde (~)
Cannot return a value or contain arguments
General destructor declaration:

~Class ( );
Class :: ~Class ( )

Declaration in class definition


Declaration in function definition

25

Computer Programming
5. Basic Object Oriented Programming

const Member Functions


It is possible that some functions will never change the
value of any member
It is desirable to declare them as const member
function
Then, the compiler will automatically check if there is
any inconsistency in the program
It helps to debug the program

Read only

In the example above, obviously GetAge() and


GetWeight() will not change any member
Hence they can be declared as const as follows:
int GetAge() const;

// add the keyword const when

int GetWeight() const; //

you declare the functions

26

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.2b
From the program you wrote in exercise 5.2a
a. Add the constructor and destructor such that the
initial age and weight of Felix is 5 and 10
respectively.
b. Use the const keyword to define the class methods
that will not modify the member variables.

27

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.2c
Identify the errors in the following program. The program
is divided into 3 parts: class declaration, member functions
implementation and the main(). Fix the errors and verify
your results by building the program.
#include <iostream>
// for cout
using namespace std;
class Cat
// begin declaration of the class
{
public:
// begin public section
Cat(int initialAge);
// constructor
~Cat();
// destructor
int GetAge() const;
// accessor function
void SetAge(int Age);
// accessor function
void Meow();
// general function
private:
int itsAge;
// member variable
};

28

Computer Programming
5. Basic Object Oriented Programming

Cat::Cat(int initialAge)
{ itsAge = initialAge;
cout << "Cat Constructor\n";
}
Cat::~Cat()
{ cout << "Cat Destructor\n";
}
int Cat::GetAge()
{ return (itsAge++);
}
void Cat::SetAge(int age)
{ itsAge = age;
}
void Cat::Meow()
{ cout << "Meow.\n";
}

int main()
{
Cat Frisky;
Frisky.Meow();
Frisky.Bark();
Frisky.itsAge = 7;
return 0;
}

29

Computer Programming
5. Basic Object Oriented Programming

Doing Business by Selling Classes


The development of Object Oriented Programming has
enabled a new business in software development
People develop different classes and sell to other
people
These classes often provide functions that are popularly
used in applications
For example, the java calculator used in some Web
pages
People post the advertisement of their classes on the Web.
Those who are interested in their classes can directly
download it and perhaps pay by credit card.

30

Computer Programming
5. Basic Object Oriented Programming

Assume that you have designed the following class CAT and
would like to sell it to a customer
#include <iostream> // for cout
using namespace std;
class Cat
// declare the class object
{
public: void SetAge (int age);
int GetAge();
void SetWeight (int weight);
int GetWeight();
private: int itsAge;
You
Youdo
donot
notwant
wantto
togive
givehim
him
int itsWeight;
the
};
thesource
sourcecodes
codesof
ofthe
themember
member
int Cat::GetAge()
{
return itsAge;
}
void Cat::SetAge(int age)
{
itsAge = age;
}

functions
functionssince
sinceyour
yourcustomer
customer
may
maycopy
copyyour
yourcodes
codes
They
Theymay
maymodify
modifyititand
andre-sell
re-sell
ititto
somebody
else
to somebody else

31

Computer Programming
5. Basic Object Oriented Programming

If the customer has the source code, he may try to modify


it by himself
It may introduce a lot of hidden errors as he knows very
little about your program
The resulting program can be very difficult to debug.
Conclusion:
Conclusion: ItItisisbetter
betterto
togive
giveyour
yourcustomer
customerexecutable
executable
codes
such
that
they
cannot
read
or
codes such that they cannot read ormodify
modifyitit
Problem
Problem1:
1: AAprogram
programwithout
withoutmain()
main()cannot
cannotbe
bebuilt.
built. No
No
executable
codes
can
be
generated
without
main()
executable codes can be generated without main()
Problem
Problem2:
2: IfIfyour
yourcustomer
customeronly
onlyhas
hasthe
theexecutable
executablecodes,
codes,how
how
can
he
know
the
way
to
use
your
class?
can he know the way to use your class?

32

Computer Programming
5. Basic Object Oriented Programming

Static Library
Header
library

Rather than giving your customer the


executable codes, you can give him a
(static) library
Inside a library, it does not contain the
executable codes, but the object codes
machine code waiting for linking
Since object codes cannot be read
directly, your customer cannot modify
your codes
To enable your customer know how to
use your class, give also your customer
a header file that contains the
definition of your class.

33

Computer Programming
5. Basic Object Oriented Programming
CatClass.h

main() of the Customer


class CAT

Main Program
MainProject.cpp
#include "CatClass.h"

public:
int GetAge();

void main()
{

};

CAT Frisky;
Age = Frisky.GetAge();
}

Explain why
public and private
Show that the
class CAT has a
public function
called GetAge()
It will return an
integer

Library
10 20 2d 35 5f 43 23
43 23

:
When the customer build the main(), it
links with CatClass.h and the library

22 6f
21 44 dd 23

Contain the
implementation
of GetAge(),
however, the
source code
cannot be seen by
the customer

34

Computer Programming
5. Basic Object Oriented Programming

Modular Program Design


Besides doing business with classes, the use of static
library also facilitates modular program design
The system analyst analyses the requirement of a
program and divides it into a number of modules
The specifications of each module, such as its functions,
the calling methods, the parameters returned, are well
defined
Based on the specifications, the development of each
module will be done by different programmers.

Very useful for teamwork

35

Computer Programming
5. Basic Object Oriented Programming

Example
step 1: obtain the requirements
The system analyst talks with the customer and obtains
the following program requirements:
A program is to be designed to show a zoo that
contains different kinds of animals, including dog,
cat, sheep, and horse
At the beginning of the program, all animals are
drawn on the screen
When user clicks on an animal, the sound of it is
played.

36

Computer Programming
5. Basic Object Oriented Programming

Example
step 2: design the program flow
Based on the
requirements,
the system
analyst designs
the program flow
using, for
example, a flow
chart.

Start
Draw animal

No

All animal drawn?

Yes
No

User click on animal?

Yes

37

Computer Programming
5. Basic Object Oriented Programming

Click Dog?

Yes

Play dog sound

No
Click Cat?

Yes

Play cat sound

No
Click Sheep?

Yes

Play sheep sound

No
Click Horse?

Yes

Play horse sound

No
Click End?

Yes

End

No

38

Computer Programming
5. Basic Object Oriented Programming

Example
step 3: divide into modules
From the flow chart, identify the classes required and
their functions
CatClass.h
HorseClass.h
DogClass.h

class CAT

SheepClass.h class HORSE


{
public:
{
class SHEEP
int DrawShape();
public:
int PlaySound(); {
int DrawShape();
public:
int PlaySound();
int DrawShape();
public:
int PlaySound(); };
int DrawShape();
};
int PlaySound();
};

class DOG

};

39

Computer Programming
5. Basic Object Oriented Programming

Example
step 4: ask programmers to
develop the modules
For each module, the system analyst will ask a programmer
to develop the codes required (to implement the class)
To speed up the process, the system analyst may ask 4
programmers to develop the modules simultaneously
The codes developed by the 4 programmers may be
different
If the specifications are correct, all modules are correct
irrespective to the difference in the codes
Hence facilitate teamwork.

40

Computer Programming
5. Basic Object Oriented Programming

Example
step 5: integrate the modules
DogClass.h

Integrating all modules by the system analyst

CatClass.h
class CAT

Main Program
MainProject.cpp
#include DogClass.h"
#include CatClass.h"
void main()
{

class CAT {
{

DOG Bobby;
CAT Frisky;
Bobby.DrawShape();
Frisky.DrawShape();

Frisky.PlaySound();
}

Library
10
20 2dfor
35};DOG
5f 43 23
43 23
10 20 2d 35 5f 43 23
43 23

:
:

Skeleton

public:
int DrawShape();
public:
int PlaySound();
int DrawShape();
int PlaySound();
Library for CAT};

22 6f
21 44 dd 23
22 6f
21 44 dd 23

41

Computer Programming
5. Basic Object Oriented Programming

Interface versus Implementation


The declaration of a class stored in the header file is in fact
a contract between the System Analyst and Programmer,
and between the developer and customer
System Analyst who wants to use the object of this class
should follow the rules defined in the declaration
Class should be implemented exactly the same way it is
declared; otherwise the customer using it will have error
C++ is strongly typed, i.e., the compiler will enforce the
contracts and set the error flag if someone violates them
In the language of OO programming, this contract is
named as interface.

42

Computer Programming
5. Basic Object Oriented Programming

Create a static library with Visual C++

Suppose you are one of the programmers and is asked to


develop the class CAT

Now, the system analyst sets out two specifications on


the class CAT:
1. It should have a function that allows the setting of
CATs age. The function is
void SetAge(int age);
2. It should have another function that allows the
reading of CATs age. The function is
int GetAge();

43

Computer Programming
5. Basic Object Oriented Programming

Step 1: Create the class required


class CAT
// declare the class
{
public: void SetAge (int age);
int GetAge();
private: int itsAge;
Based
Basedon
onthe
the
};

specifications,
specifications,
you
youmay
may
design
designthe
the
above
class
above class
CAT
CAT

44

Computer Programming
5. Basic Object Oriented Programming

Step 2: Implement the class


class CAT
// declare the class
{
public: void SetAge (int age);
int GetAge();
private: int itsAge;
};
To be put to header file
int CAT::GetAge()
{
return itsAge;
}
void CAT::SetAge(int age)
{
itsAge = age;
}

For
Foreach
eachmember
member
function,
develop
function, developthe
the
required
requiredcodes
codesfor
for
building
the
library
building the library
Keep
Keepthis
thisrestricted
restricted

45

Computer Programming
5. Basic Object Oriented Programming

Step 3: Test the class


Create
Createthe
theheader
headerfile
fileand
andaamain()
main()for
fortesting
testingthe
the
functionality
functionalityof
ofthe
theclass
class
This
Thismain()
main()isisonly
onlyfor
fortesting
testingpurpose,
purpose,not
notsupposed
supposedto
to
be
beused
usedin
inreal
realapplication
application
MainTest.cpp
CatClass.h
class CAT
{
public: void SetAge (int age);
int GetAge();
private: int itsAge;
};

#include <iostream>
using namespace std;
#include "CatClass.h"
// --- put implementation here
int main()
{
CAT Frisky;
Frisky.SetAge(7);
int Age = Frisky.GetAge();
cout << Age << endl;
return 0;
}

46

Computer Programming
5. Basic Object Oriented Programming

Step 4: Create library with Visual C++


Assume your class is fully tested. You can create your
library using Visual C++
Start your Visual C++ 2010
In Visual C++ 2010, start a new project as usual
Set the location to store your library project to, e.g.
e:\VS_Proj\ENG236\Ch5
Set the project name, e.g. LibCat
However, when choosing the Application type in
the Application Settings window, choose
Static library and uncheck the option
Precompiled header

47

Computer Programming
5. Basic Object Oriented Programming

48

Computer Programming
5. Basic Object Oriented Programming

In Visual C++ 2010 Solution Explorer, under Header


Files, right-click Add New Item ... and
choose Header File (.h)
Set the Header File name to, e.g. CatClass
Click Add and the header file CatClass.h will be
added to the project LibCat
Type the class declaration

49

Computer Programming
5. Basic Object Oriented Programming

Type
Typeyour
yourclass
classdeclaration
declarationhere
here
Remember
to
comment
your
Remember to comment yourcodes
codes

50

Computer Programming
5. Basic Object Oriented Programming

In Visual C++, click Project/Add New Item... and


choose C++ File (.cpp)
Set the C++ source file name, e.g. CatCodes
Click OK and the C++ source file CatCodes.cpp will be
added to the project LibCat
You may verify it by checking the Solution Explorer
Type the codes for the implementation of the member
functions
Remember to include your header file and be careful of its
location
Build the library by clicking Build Solution.
Give LibCat.lib

51

Computer Programming
5. BasicObject
You Oriented
need toProgramming
enter the correct

You need to enter the correctpath


pathof
ofthe
theheader
headerfile
file
ItItshows
that
the
CatClass.h
is
in
the
current
shows that the CatClass.h is in the current
folder
folderof
ofCatCodes.cpp
CatCodes.cpp

Solution
Explorer
window
After
Afterbuilding
buildingthe
thelibrary,
library,the
theresult
resultisisshown
shown

52

Computer Programming
5. Basic Object Oriented Programming

Step 5: Send the library and header


file to the System Analyst
Locate the files CatClass.h and LibCat.lib and
send to the System Analyst
CatClass.h shows the class definition
From its contents, the System Analyst knows how to
use the class
LibCat.lib contains the codes for the
implementation of the member functions
It is in object code form such that even the System
Analyst cannot interpret or modify the codes.

53

Computer Programming
5. Basic Object Oriented Programming

e:\Vs_Proj\ENG236
e:\Vs_Proj\ENG236
\Ch5\LibCat\debug
\Ch5\LibCat\debug

e:\Vs_Proj\ENG236\Ch
e:\Vs_Proj\ENG236\Ch
5\LibCat\LibCat
5\LibCat\LibCat

54

Computer Programming
5. Basic Object Oriented Programming

Step 6: Integrating into the application


Open a Win32 Console project, e.g. MainProject in the
folder e.g. e:\VS_Proj\ENG236\Ch5\
Enter the codes for the main() and other functions if
necessary to implement the application
Prog.cpp
Copy CatClass.h and LibCat.lib sent from the
programmer to current folder
e:\VS_Proj\ENG236\Ch5\MainProject\MainProject
In Visual C++, click Project/Add Existing Item...
under MainProject. Select All Files to show all the files
in the folder
Add CatClass.h and LibCat.lib to the project
Build Solution and run the application.

55

Computer Programming
5. Basic Object Oriented Programming

After
Afterbuilding
buildingthe
the
application,
the
application, theresult
resultisis
shown
shown

56

Computer Programming
5. Basic Object Oriented Programming

You
Youmay
maydouble-click
double-click
LibCat.lib.
LibCat.lib.You
Youcan
can
only
see
some
hex
codes.
only see some hex codes.No
No
source
sourcecodes
codescan
canbe
befound
found

See
Seethe
theadded
added
CatClass.h
CatClass.hand
and
LibCat.lib
LibCat.libhere
here

57

Computer Programming
5. Basic Object Oriented Programming

To
Tosee
seehow
howto
touse
usethe
theclass
classCAT,
CAT,
double-click
double-clickCatClass.h
CatClass.h

58

Computer Programming
5. Basic Object Oriented Programming

Avoiding Multiple Inclusion of Header Files


z

often several program files use the same header file containing
typedef statements, constants, or class type declarations--but, it is a
compile-time error to define the same identifier twice

this preprocessor directive syntax is used to avoid the compilation


error that would otherwise occur from multiple uses of #include for
the same header file

#ifndef Preprocessor_Identifier
#define Preprocessor_Identifier
.
.
.

#endif

59

Computer Programming
5. Basic Object Oriented Programming

Using Preprocessor Directive #ifndef


// timetype .h
// SPECIFICATION FILE
#ifndef TIME_H
#define TIME_H
class TimeType
{
public:

FOR COMPILATION THE CLASS DECLARATION IN


FILE timetype.h WILL BE INCLUDED ONLY ONCE

// timetype .cpp
// IMPLEMENTATION FILE

// client.cpp
// Appointment program

#include timetype.h

#include timetype.h

. . .

. . .

int main ( void )


{

private:

. . .

. . .

};
#endif

60

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.3 - Requirements

Write a program using Visual C++ to do the following:

A class CAT must be created and your program will repeatedly


ask user to choose one of the following
a. Set the weight of a cat
b. Get the weight of a cat
c. Ask the cat to Meow!
d. Quit
If the user chooses (a), the user will be asked to input the weight
of the cat and the program will store it up

If the user chooses (b), the weight of the cat will be shown on the
screen

If the user chooses (c), show the following message on the screen
Meow, Meow ... Meow

If the user chooses (d), quit the program.

61

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.3 (cont.) - Activity


1.

Two students in a group. One plays the role of a System Analyst.


One plays the role of a Programmer

2.

The System Analyst should design the program structure using


flow chart and define the specifications of the class required

3.

The Programmer should develop the class and build a library


(with the header file required). You may email your library file
and header file to the System Analyst

4.

After receiving the files from the Programmer, the System


Analyst should integrate them into the application

5.

Show the result to your tutor.

62

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.3b - Requirements

Write a program using Visual C++ to do the following:

A class PHONE must be created and your program will


repeatedly ask user to choose one of the following
a. Set the serial no. of a phone
b. Get the serial no. of a phone
c. Ask the phone to ring!
d. Quit
If the user chooses (a), the user will be asked to input a 6-digit
serial no. of the phone and the program will store it up

If the user chooses (b), the 6-digit serial no. of the phone will be
shown on the screen

If user chooses (c), show the following message on the screen


Ring ... Ring, Ring ... Ring

If user chooses (d), quit the program.

63

Computer Programming
5. Basic Object Oriented Programming

Exercise 5.3b (cont) - Activity


1. For the same group, interchange the role of group
members. The Programmer will play the role of System
Analyst now; and the System Analyst will play the role of
Programmer now
2. The System Analyst should design the program structure
using flow chart and define the specifications of the class
required
3. The Programmer should develop the class and build a
library (with the header file required). You may email your
library file and header file to the System Analyst
4. After receiving the files from the Programmer, the System
Analyst should integrate them into the application

64

Computer Programming
6. Pointers and Arrays

How memory is used in C++?


The whole big piece of memory is divided into 4
areas:
Code Space - for the storage of program code
Stack - for the storage of local variables, passed
parameters.
Global Name Space - for the storage of global
variables
Free store - for the storage of dynamically
created data

65

Computer Programming
6. Pointers and Arrays

How memory is used in C++?


main()
{ Statements;
funcA();
Statements;
funcB();
Statements;
}

Free Store
or
the heap

funcA()
{ int a;
return;
}

The Stack
Code Space
Global Name Space

funcB()
{ Cat Frisky;
return;
}

66

Computer Programming
6. Pointers and Arrays

What is the Address of a Variable?


A variable is a storage space in memory Each byte has an address
Every variable has a memory address
Variables char a
Memory
Address

int b

30 0A 21 3A

Each variable has the


starting-byte address

short int c

bool d

51

00

44 20

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109
The character '0'

a = 30

Address of a = 0100

b = 0A 21 3A 51 Address of b = 0101
c = 44 20

Address of c = 0105

All values written in


hexadecimal but
binary in reality

67

Computer Programming
6. Pointers and Arrays

What is the Address of a Variable?


In C++, the symbol & is used to indicate the address of a
#include <iostream>
variable

The
Theaddresses
addressesof
of
shortVar,
shortVar,
longVar
longVarand
and
sVar
sVar

using namespace std;


int main()
{
unsigned short shortVar = 5;
unsigned long longVar = 65535;
long sVar = -65535;
cout << "shortVar:\t" << shortVar;
cout << "\tAddress of shortVar:\t";
cout << &shortVar << "\n";
cout << "longVar:\t" << longVar;
cout << "\tAddress of longVar:\t";
cout << &longVar << "\n";
cout << "sVar:\t\t" << sVar;
cout << "\tAddress of sVar:\t";
cout << &sVar << "\n";
return 0;
}

68

Computer Programming
6. Pointers and Arrays

What is the Address of a Variable?


Variable and address of a variable are different

69

Computer Programming
6. Pointers and Arrays

What is a Pointer?
In many situations, we want to store the address of a
variable into a particular memory location
Variables char a
Memory
Address

int b

10 0A 21 3A

(address of a) pa
51

00

00 01

00

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109
pa is the pointer of a

pa is a variable that can store the address of a


In C++, every address has 4 bytes. So we need to reserve 4
bytes of memory to store the address of a .

70

Computer Programming
6. Pointers and Arrays

What is a Pointer?
In C++, every variable needs to have its type declared
int abc; // means abc belongs to the type of integer
CAT Felix; // means Felix belongs to the class CAT
If we want to declare the type of pa, which stores the
address of a variable a, how should we do it?
How about

address pa;

Not
Notgood
goodenough,
enough,since
sinceititdoes
doesnot
nottell
tellthe
thenature
natureof
ofaa
How about

(address of a character) pa;

Better,
Better,but
butlook
looktoo
tooclumsy
clumsy

71

Computer Programming
6. Pointers and Arrays

What is a Pointer?
C++ uses an elegant way to solve the problem (but need
some time to understand!)

pa's content is an address, the memory

It introduces a symbol *
content of that address is a character
means the content of an address
Variables char a
Memory
Address

int b

10 0A 21 3A

char *pa
51

00

00 01

00

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109

char *pa indicates that the memory content of the


address stored in pa is a character. pa is indirectly
declared to be an address of character.

72

Computer Programming
6. Pointers and Arrays

What is a Pointer?

We can modify the content of a memory location using


pointer
Variables char a int b
char *pa
Memory
Address

30 0A 21 3A

51

00

00 01

00

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109

char *pa, a=0x30; // 48


cout << a;
// a = '0'
pa = &a;
// pa = 0100
cout << *pa; // *pa = '0'
*pa = 49;
// a = '1'
cout << a;

We
Wemodify
modifyaaindirectly
indirectlyby
by
using
usingits
itsaddress
address

73

Computer Programming
6. Pointers and Arrays

Pointers
z
z
z

Special variables that only hold memory addresses


Hold the location (address) of information, not the
information itself
Pointers are declared using a * after the type
int a = 10;
int * p;

//

A POINTER VARIABLE!!!!

p = &a;

You have to specify the pointer type!

74

Computer Programming
6. Pointers and Arrays

Dont get confused


z
z
z

pointer p does not hold the value of a


it points to the memory location of a
pointer p is a variable

and it has its own memory location


a

1048572

1048573

1048575

1048574

1048571

000002

000001

000000

Pointer Constants

1048570

75

Computer Programming
6. Pointers and Arrays

Examples

76

Computer Programming
6. Pointers and Arrays

Pointer
Indirection
(Pointer to Pointer)

What is the result?


58 58 58

int x=7; int *p, *q;


p = &x; q = &x;

77

Computer Programming
6. Pointers
and Arrays
#include
<iostream>
using namespace std;
typedef unsigned short int USHORT;
int main()
{
USHORT myAge;
// a variable
USHORT * pAge = 0;// a null pointer, pAge=0, not *pAge=0
// Dont let it become wild pointer (point to unknown)
myAge = 5;
cout << "myAge: " << myAge << "\n";
pAge = &myAge; // assign address of myAge to pAge
cout << "*pAge: " << *pAge << "\n\n";
cout << "*pAge = 7\n";
*pAge = 7;
// *pAge=7, not pAge=7, sets myAge to 7
cout << "*pAge: " << *pAge << "\n";
cout << "myAge: " << myAge << "\n\n";
cout << "myAge = 9\n";
myAge = 9;
cout << "myAge: " << myAge << "\n";
cout << "*pAge: " << *pAge << "\n";
return 0;
}

78

Computer Programming
6. Pointers and Arrays

79

80

Computer Programming
6. Pointers and Arrays

Why Pointer? - Using Free Store


Pointer allows us to handle the memory in Free Store
The memory Free Store is opened to all functions
Pointer helps us to identify the part of memory in Free
Store that is being used by a particular function or object
To use the memory in Free Store:
1. Claim to the system how much memory is required
2. System allocates a memory space with size big enough
3. System returns a pointer value which is the starting
address of that memory space
4. When the memory space is not required, release it back
to the system for other functions.

81

Computer Programming
6. Pointers and Arrays

new operator
z

General form:
new type [num_elements]

type is data type of array elements


num_elements is number of array elements

Reserves memory but does NOT fill with values

new returns address of memory it reserves


Value assigned to pointer variable of same type

int* array_address;
array_address = new int [10];
array_address[0], array_address[9]
*array_address, *(array_address+9)

82

Computer Programming
6. Pointers and Arrays

new and delete


The keywords new and delete help us claim and release
memory in Free Store
Claim a piece of memory in

Claim a piece of memory in


unsigned short int * pPointer;
Free
FreeStore
Storewith
withsize
sizethat
thatisis
pPointer = new unsigned short int;
equal
equalto
toan
anunsigned
unsignedshort
short
:
integer
// after using the memory space
integer
:
delete pPointer; // return it to system
We
Weclaim
claimmemory
memorywith
withsize
size
equals
to
2
integers.
equals to 2 integers.
pPointer2
pPointer2now
nowpoints
pointsto
tothe
the
starting
address
of
this
starting address of this
memory
memoryspace
space

int * pPointer2;
pPointer2 = new int[2];
:
// after using the memory space
:
delete [] pPointer2; // return it to system

Results
Resultsunpredictable
unpredictableififno
no[]
[]

83

Computer Programming
6. Pointers and Arrays

delete operator
z

General form:
delete [ ] array_address;

z
z
z

array_address is pointer variable

Releases memory stored at address indicated


Knows size of memory reserved by new and
releases memory for all the array
delete address;

deletes memory for single element

84

Computer Programming
6. Pointers and Arrays

int * pPointer;
unsigned short int * pPointer2;
pPointer
pPointer==8004
8004
pPointer = new int;
:
pPointer2 = new unsigned short int [2]; pPointer2
pPointer2==8008
8008
:
delete pPointer; // return it to system
delete [] pPointer2; // return it to system

Free Store
Memory
Address

8003 8004 8005 8006 8007 8008 8009 800A 800B 800C

85

Computer Programming
6. Pointers and Arrays

Null Address
z

0 is a constant pointer that represents the empty


or null address

Its value indicates that pointer is not pointing to any


valid object

Cannot dereference a pointer whose value is null


int *ptr = 0;
cout << *ptr << endl; // invalid, ptr
// does not point to
// a valid int

86

Computer Programming
6. Pointers and Arrays

Dangling Pointers and Memory Leaks


z

A pointer is dangling if it contains the address of


memory that has been freed by a call to
delete.

Solution: set such pointers to 0 as soon as memory


is freed.

A memory leak occurs if no-longer-needed


dynamic memory is not freed. The memory is
unavailable for reuse within the program.

Solution: free up dynamic memory after use


10-86

Computer Programming
6. Pointers and Arrays

Dangling Pointer
int *A = new int[5]; //int *A; A=new int[5];
for (int i = 0; i < 5; ++i) A[i] = i;
int *B = A;
//int *B; B=A;
A
0

delete [] A;
Locations do not belong to program
A

?
B

Computer Programming
6. Pointers and Arrays

Memory Leak
int *A = new int [5];
for (int i = 0; i < 5; ++i) A[i] = i;
A

A = new int [5];


These locations cannot be
accessed by program
A

89

Computer Programming
6. Pointers and Arrays

Stray (Wild or Dangling) Pointers

When one deletes a pointer, the associated memory will


be given back to system delete a pointer remove a pointer, it still exists

If one tries to use that pointer again without reassigning


it, the result is unpredictable
NULL points to ROM
To ensure one will not use the deleted pointer again,
always assign the pointer with the value 0 after delete
A stray (or wild, dangling) pointer is the pointer that has
been deleted but without assigning to null
int *pNum = new int(5);

// Initialize *pNum to 5

delete pNum;
pNum = 0;

// To ensure the program will crash rather


// than unpredictable if one reuses it

90

Computer Programming
6. Pointers and Arrays

Exercise 6.1
The program on the next page will introduce the problem of
memory leaks (the system cannot get back the memory
allocated to the program) and execution error. Build the
program and step over each line of code using the Run-time
Debugger. Answer the following questions:
1. What is the address of localVariable?
2. What is the value of pHeap after executing line 6?
3. What is the value of pHeap after executing line 11?
4. Assume that you can finish executing the program. Do
you think you can free the memory claimed by the new
statement in line 6? If no, why not?
Modify the program such that we can free the memories
claimed by both new statements in line 6 and line 11.

91

Computer Programming
6. Pointers and Arrays

#include <iostream>
using namespace std;
int main()
{
int localVariable = 5;
int * pLocal = &localVariable;
int * pHeap = new int; //line 6
*pHeap = 7;
cout << "localVariable: " << localVariable << "\n";
cout << "*pLocal: " << *pLocal << "\n";
cout << "*pHeap: " << *pHeap << "\n";
pHeap = new int; //line 11
*pHeap = 9;
cout << "*pHeap: " << *pHeap << "\n";
delete pHeap;
delete pHeap;
return 0;
}

92

Computer Programming
6. Pointers and Arrays

Creating Objects in the Free Store


Similar to integer, we
can create objects in
the Free Store

Size enough for a Cat

Cat *pCat = new Cat;

pCat stores the


beginning address of
the memory allocated
When the object is
created, its
constructor is called
Object identified by a pointer.

Free Store
or
the heap

pCat

The Stack
Code Space
Global Name Space

93

Computer Programming
6. Pointers and Arrays

Deleting Objects
Objects in the Free Store can also be deleted
Cat *pCat = new Cat;
delete pCat;

pCat becomes an identifier of the object created


When an object is deleted, its destructor will be called
Hence the destructor of Cat will be called when the
keyword delete is used in the above
(The destructor will also be called if the function that
creates the object finishes.)

94

Computer Programming
6. Pointers References and Arrays

#include <iostream>
using namespace std;
class SimpleCat
{
public:
SimpleCat();
~SimpleCat();
int GetAge() const {return itsAge;}
void SetAge(int age) {itsAge = age;}
private:
int itsAge;
};
SimpleCat::SimpleCat()
{ cout << "Constructor called.\n";
itsAge = 1;
}
SimpleCat::~SimpleCat()
{ cout << "Destructor called.\n";
}

Example
The class
SimpleCat

Constructor

Destructor

95

Computer Programming
6. Pointers and Arrays

int main()
{
cout << "SimpleCat Frisky...\n";
SimpleCat Frisky;
cout << "SimpleCat *pRags = new SimpleCat...\n";
SimpleCat * pRags = new SimpleCat;
pRags in
cout << "delete pRags...\n";
the stack,
delete pRags;
cout << "Exiting, watch Frisky go...\n"; *pRags in
return 0;
the heap
}

Output of the
program

96

Computer Programming
6. Pointers and Arrays

Accessing Members of Objects


To access members of an object, the operator (.) is used
The
The
Same
Same

SimpleCat *pCat = new SimpleCat;


(*pCat).SetAge(2);

The object
The member
pointed by pCat function of the
object

Input parameter
of the member
function

In C++, a shorthand is provided for such member access


SimpleCat *pCat = new SimpleCat;
pCat->SetAge(2);

// The same as before

97

Computer Programming
6. Pointers and Arrays

Pointers to Objects
z

Special arrow operator

z
z
z

->

Negative and greater than symbol with no space between


Used to access members with object's address

Declaring pointer Class_name* ptr_name;


Initializing pointer ptr_name = &object_name;
Calling member function (2 argument example)
ptr_name -> member_fun(arg1, arg2);
(*ptr_name).member_fun(arg1, arg2);
ptr_name[0].member_fun(arg1,arg2);

98

Computer Programming
6. Pointers
and Arrays
#include
<iostream>
using namespace std;
class Object
{
public:
Object();
~Object();
int GetCnt()
const {return *count;}
private:
int *count;
};
Object::Object()
{ count = new int(1);
} // initialize *count to 1
Object::~Object()
{ delete count;}
int main()
{ Object Obj;
return 0;
}

Question
If I declare an object in
the stack that has
member variables in the
heap, what is in the
stack and what is in the
heap?

99

Computer Programming
6. Pointers and Arrays

Answer
4 bytes: *count

Free Store
or
the heap

4 bytes on the stack to


hold Obj which
contains a pointer
count
4 bytes on the heap that
is pointed by count of
Obj

Obj
Obj
4 bytes: count The Stack
Code Space
Global Name Space

100

Computer Programming
6. Pointers and Arrays

Using the this Pointer


Can be used to access members that may be
hidden by parameters with the same name:
class SomeClass
{
private:
int num;
public:
void setNum(int num)
{ this->num = num; }
};

101

Computer Programming
6. Pointers and Arrays

Pointers Arithmetic
Pointers can be added or subtracted from one another
if they are of the same type
Variables short int *a, *b
Memory
Address

10 0A 21 3A 51 44 20
0000 0001 0002 0003 0004 0005 0006 0007 0008 0009

cout << "a = " << a << endl;

// Assume a = 0000

b = a + 1;
cout << "b = " << b << endl;

// b = 0002

cout << "b - a = " << b-a << endl;

// b - a = 1

102

Computer Programming
6. Pointers and Arrays

Pointer Variables and Arithmetic


z

Declare variable as pointer


double* b;

Holds address

Can perform addition and subtraction

Purpose of add is to advance to subsequent cell


b + 1 (double is 8 bytes, so adds 8 bytes)
Subtraction goes back to previous memory cell
b 1 (goes back 8 bytes)

103

Computer Programming
6. Pointers and Arrays

Pointers Arithmetic
The same applies to objects

You should not DIRECTLY assign a


value to a pointer, e.g.
int *p=0x00110110;

Variables Cat *a = new Cat; //Assume Cat takes 6 bytes

Memory
Address

0000 0001 0002 0003 0004 0005 0006 0007 0008 0009

Cat *a = new Cat;


Cat *b;
cout << "a = " << a << endl;
// Assume a = 0000
b = a + 1; // Don't touch *b as the memory is not from new
cout << "b = " << b << endl;
// b = 0006
cout << "b - a = " << b-a << endl;
// b - a = 1

104

Computer Programming
6. Pointers and Arrays

Exercise 6.1b
Find out the errors in the following programs. Note the
error messages when you build these program. Fix the
errors and rebuild it to verify your corrections.
#include <iostream>
using namespace std;
int main()
{
int *pInt;
*pInt = 9;
cout <<
"The value at pInt: "
<< *pInt << endl;
return 0;
}

#include <iostream>
using namespace std;
int main()
{
int SomeVariable = 5;
cout << "SomeVariable: "
<< SomeVariable << "\n";
int *pVar = & SomeVariable;
pVar = 9;
cout << "SomeVariable: " <<
*pVar << "\n";
return 0;
}

105

Computer Programming
6. Pointers and Arrays

Exercise 6.1c
Modify the program you wrote in exercises 5.2 a and b such that
a. The program will ask the user if he wants to create the object Felix. If
yes, the object is created in the heap. If no, just quit.
b. As before, initialize the age and weight of Felix to 5 and 10 using the
constructor. Display the age and weight of Felix.
c. Ask the user to enter the age and weight of Felix and display them
again.
d. After printing the age and weight of Felix, the program will
repeatedly ask the user whether he wants to (i) enter the age and weight
again; (ii) destroy Felix and create again; or (iii) quit the program.
Your program should be able to perform the task the user selected.
e. Whenever Felix is destroyed, print the current age and weight of
Felix using the destructor
f. Comment your program appropriately.

106

Computer Programming
6. Pointers and Arrays

What Is an Array?

In consecutive memory

An array consists of a collection of data storage


locations, each holds the same type of data
An array can be easily declared as follows:
short shortArray[25];

Variables short
Memory

shortArray[25]; //declaration

10 0A 21 3A

shortArray[0]

ItItstates
statesthat
thatthere
thereisisaasequence
sequenceof
of25
25
short
integer
data.
The
whole
short integer data. The whole
sequence
sequenceisisnamed
namedas
asshortArray
shortArray

...

... 20 2A 4B 40

000B
000C ...
... 0037 0038 0039
003A
shortArray[1]
shortArray[24]

107

Computer Programming
6. Pointers and Arrays

Array Element
In an array, an array element is referred to by indicating
its index
The first element has index 0, and then 1,
Hence

shortArray[0] is the first element


shortArray[1] is the second element 25 short
25 short
integers
integers
:
shortArray[24] is the last element

No shortArray[25] !!!
Do not try to use shortArray[25], result
unpredictable.

108

Computer Programming
6. Pointers and Arrays

short shortArray[25];

Variables short

Declaration

shortArray[25];

Memory

10 0A 21 3A ... ... 20 2A 4B 40
Address
0009 000A 000B 000C ...
... 0037 0038 0039 003A
(Hex)
So shortArray[0] = 0x100A;// 4106 in deciaml
shortArray[1] = 0x213A;// 8506 in decimal
:
shortArray[23] = 0x202A;
shortArray[24] = 0x4B40;

Assignment
statements

109

Computer Programming
6. Pointers and Arrays

Assigning Values to Individual Array Elements


float temps[ 5 ] ;
int m = 4 ;
temps[ 2 ] = 98.6 ;
temps[ 3 ] = 101.2 ;
temps[ 0 ] = 99.4 ;
temps[ m ] = temps[ 3 ] / 2.0 ;

7000

99.4
temps[0]

7004

// allocates memory for array

7008

98.6

temps[1]

temps[2]

7012

101.2
temps[3]

7016

50.6
temps[4]

110

Computer Programming
6. Pointers and Arrays

No
NomyArray[5]
myArray[5]!!!
!!!
Do
Donot
nottry
tryto
touse
usemyArray[5],
myArray[5],
result
resultunpredictable
unpredictable

#include <iostream>
using namespace std;
int main()
{
int myArray[5],i;
for (i=0; i<=5; i++)
The
Thekind
kindof
ofmistake
mistake
myArray[i] = 20;
people
often
people oftenmake
make
for (i=0; i<5; i++)
cout << myArray[i] << endl;
return 0;
}

111

Computer Programming
6. Pointers and Arrays

Example more definitions


Suppose
const
const
const
const

int
int
int
int

N = 20;
M = 40;
MaxStringSize = 80;
MaxListSize = 1000;

Then the following are all correct array definitions


int A[10];
// array of
char B[MaxStringSize];
// array of
double C[M*N];
// array of
int Values[MaxListSize]; // array of

10 ints
80 chars
800 floats
1000 ints

112

Computer Programming
6. Pointers and Arrays

Initializing Arrays
An array can be initialized during declaration
int IntegerArray[5] = {10,20,30,40,50};
int AnotherArray[] = {50,40,30,20,10};
int BiggerArray[5] = {10,20};

IntegerArray
IntegerArraydeclares
declares
itself
to
have
5
integers
itself to have 5 integers

AnotherArray
AnotherArrayrequests
requeststhe
thememory
memory
space
in
stack
just
enough
to
hold
space in stack just enough to holdthe
the
data
defined
in
the
list
data defined in the list
BiggerArray
BiggerArraydeclares
declaresitself
itselfto
tohave
have
55integers
int a[5]; NOT the same
integersbut
butonly
onlythe
thefirst
first22of
ofthem
them
are
as int a[5]={};
areinitialized.
initialized.The
Theothers
othersare
are0.
0.
ItItisisdifferent
differentfrom
from:: int BiggerArray[] = {10,20};
int IncorrectArray[2] = {10,20,30};

113

Computer Programming
6. Pointers and Arrays

Copying One Array to Another


z

Cannot copy with an assignment statement:


tests2 = tests;

//wont work

Must instead use a loop to copy element-byelement:


for (int i=0; i < SIZE; i++)
tests2[i] = tests[i];

8-113

114

Computer Programming
6. Pointers and Arrays

Passing Arrays to Functions


To pass an array argument to a function, specify the name of the array
without any brackets
int myArray[ 24 ];
...
myFunction( myArray, 24 );
...

Pass array name


Size is also often sent as an argument

Array size usually passed to function

Arrays passed call-by-reference


The called functions can modify the element values in the callers original
array
Name of array is the address of first element of the array
Function knows where the array is stored. Therefore, when the called
function modifies array elements in its function body, it is modifying the
actual elements of array in the original memory locations

main()
myFunction()

myArray

115

Computer Programming
6. Pointers and Arrays

Use of const
z

because the identifier of an array holds the base


address of the array, an & is never needed for an
array in the parameter list

arrays are always passed by reference

to prevent elements of an array used as an


argument from being unintentionally changed by the
function, you place const in the function heading
and prototype

116

Computer Programming
6. Pointers and Arrays

Passing An Array

Notice brackets are empty

int Minimum(const int A[], int size)


{
int SmallestValueSoFar = A[0];
First element
for (int i = 1; i < size; ++i)
if (A[i] < SmallestValueSoFar )
SmallestValueSoFar = A[i];
return SmallestValueSoFar ;

}
int Number[6] ={3, 88, -7, 9, 1, 24};
cout << Minimum(Number, 6) << endl;
int List[3];
List[0] = 9;
List[1] = 12;
List[2] = 45;
cout << Minimum(List, 3) << endl;

117

Computer Programming
6. Pointers and Arrays

Example with Array Parameters


#include <iostream>
using namespace std;
void Obtain ( int [ ], int ) ; // prototypes here
void Print ( const int [ ], int ) ;
using namespace std ;
int main( )
{

int
int

temp[31] ;
numDays;

// array to hold up to 31 temperatures

cout << How many daily temperatures? ;


cin >> numDays ;
Obtain( temp, numDays ) ;

// call passes value of numDays and


// address of array temp to function

cout << numDays << temperatures << endl ;


Print ( temp, numDays ) ;
return 0 ;
}

118

Computer Programming
6. Pointers and Arrays

Array of Objects
Any object can be stored in an array
Accessing member data in an array of objects is a twostep process

Identify the member of array by []

Access the member by .

CAT Litter[5]; //Litter[0] - Litter[4] are 5 objects


int i;
for (i=0; i<5; i++)
cout << Litter[i].GetAge() << endl;

To
Tofind
findout
outwhich
whichCAT
CAT

Call
CallGetAge()
GetAge()of
ofthat
thatCAT
CAT

119

Computer Programming
6. Pointers and Arrays

Multi-dimensional Array
It is possible to have an array of more than 1 dimension
7
6
5
4

A 2-dimensional array
can be declared as
int Board[8][8]; 64 integers

3
2
1
0

0 1 2 3 4 5 6 7

Two-dimensional
Two-dimensionalarray
array
AAChess
Board
Chess Board

Each element can be


written or read as
Board[5][3] = 0;
int number = Board[5][3];
// number = 0

120

Computer Programming
6. Pointers and Arrays

Processing Two-Dimensional Arrays


z

Two-dimensional arrays can be initialized in


the declaration by listing values within braces,
separated by commas

Braces can be used to distinguish rows, but are not


required

int val[ ][4] = { 8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10 }

121

Computer Programming
6. Pointers and Arrays

Initialize Multidimensional Arrays


Multidimensional Arrays can also be initialized during
declaration
int SomeArray[5][2] = { {0,0},{1,2},{4,6},{7,2},{4,4}};
int AnotherArray[5][2] = {0,0,1,2,4,6,7,2,4,4};

7
4

2
6

2
1
0

1 2
0 0
0 1

SomeArray[0]{0, 0}
SomeArray[1]{1, 2}
SomeArray[2]{4, 6}
SomeArray[3]{7, 2}
SomeArray[4]{4, 4}
SomeArray[2][1] = *(SomeArray[2]+1)
= *( *(SomeArray+2) + 1) = 6

122

Computer Programming
6. Pointers and Arrays
const int NUM_STATES = 50 ;
const int NUM_MONTHS = 12 ;
int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ;

STORAGE
z

rows

columns

In memory, C++ stores arrays in row order. The first


row is followed by the second row, etc.

Base Address
8000

8048

8096
..

12 highs for state 0

12 highs for state 1

first row

second row

etc.

123

Computer Programming
6. Pointers and Arrays

Viewed another way . . .


stateHighs[ 0 ] [ 0 ]
stateHighs[ 0 ] [ 1 ]
stateHighs[ 0 ] [ 2 ]
stateHighs[ 0 ] [ 3 ]
stateHighs[ 0 ] [ 4 ]
stateHighs[ 0 ] [ 5 ]
stateHighs[ 0 ] [ 6 ]
stateHighs[ 0 ] [ 7 ]
stateHighs[ 0 ] [ 8 ]
stateHighs[ 0 ] [ 9 ]
stateHighs[ 0 ] [10 ]
stateHighs[ 0 ] [11 ]
stateHighs[ 1 ] [ 0 ]
stateHighs[ 1 ] [ 1 ]
stateHighs[ 1 ] [ 2 ]
stateHighs[ 1 ] [ 3 ]
.
.
.

Base Address 8000

To locate an element such as


stateHighs [ 2 ] [ 7]
the compiler needs to know
that there are 12 columns
in this two-dimensional array.

At what address will


stateHighs [ 2 ] [ 7 ] be found?
Assume 4 bytes for type int.

124

Computer Programming
6. Pointers and Arrays

void FindAverages( /* in */ const int stateHighs [ ] [ NUM_MONTHS] ,


/* out */
int stateAverages [ ] )
{

int
int
int
for

}
}

state;
month;
total;
( state = 0 ; state < NUM_STATES; state++ ) {
total = 0 ;
for ( month = 0 ; month < NUM_MONTHS ; month++ )
total += stateHighs [ state ] [ month ] ;
stateAverages [ state ] = int ( total / 12.0 + 0.5 ) ;

125

Computer Programming
6. Pointers and Arrays

Matrix Addition Solution


Notice only first
brackets are empty

void MatrixAdd(const float A[][MaxCols],


const float B[][MaxCols], float C[][MaxCols],
int m, int n)
{
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
C[i][j] = A[i][j] + B[i][j];
}

126

Computer Programming
6. Pointers and Arrays
const NUM_DEPTS
= 5;
const NUM_MONTHS = 12 ;
const NUM_STORES = 3 ;

// mens, womens, childrens, electronics, furniture


// White Marsh, Owings Mills, Towson

int monthlySales [ NUM_STORES ] [ NUM_DEPTS ] [ NUM_MONTHS ] ;


monthlySales[0][3][7]
sales
for
electronics in August at White Marsh
S

5 DEPTS
rows

RE
O
ST eets
3 sh

12 MONTHS columns

127

Computer Programming
6. Pointers and Arrays

Array and Pointer


C++ allows the flexibility for user to use Array and
Pointer interchangeably
The name of an array is a constant pointer
pointing to the first element of the array
int
int
a =
b =

a,b;
SomeArray[5] = {10,20,30,40,50};
*SomeArray;
// a = 10
*(SomeArray+1); // b = 20, pointer arithmetic

Compiler does all the calculation


SomeArray+1 does not add 1 to SomeArray but add 4
(1 integer needs 4 bytes for storage) and point to the
next element in the array

128

Computer Programming
6. Pointers and Arrays

SomeArray[5]
The Stack
Address

10 20

30

40

50

0100 0104 0108 010c 0110 0114 0118 011c 0120 0124

There is NOT a memory location to store the pointer


SomeArray. Everything is done by an internal conversion
xx == *SomeArray;
*SomeArray;
will
willbe
beinternally
internallyconverted
convertedto
to
xx == SomeArray[0];
//
x
=
SomeArray[0];
// x = 10
10
px
px == SomeArray;
SomeArray;
will
willbe
beinternally
internallyconverted
convertedto
to
px
=
&(SomeArray[0]);
//
px = &(SomeArray[0]);
// px
px == 0104
0104

129

Computer Programming
6. Pointers and Arrays

A variable declared as a pointer can also be used as an array


int SomeArray[5] = {10,11,12,13,14};
int *pSomePointer = SomeArray; // It is a pointer but will
// later be used as array
cout << pSomePointer[0] << endl; // number 10 will be shown
cout << pSomePointer[1] << endl; // number 11 will be shown
cout << pSomePointer[2] << endl; // number 12 will be shown
cout << pSomePointer[3] << endl; // number 13 will be shown
cout << pSomePointer[4] << endl; // number 14 will be shown
SomeArray[1] and
pSomePointer[1]
are exactly the same.

SomeArray[]

pSomePointer

0104
The stack
10 11 12 13 14
Address 0100 0104 0108 010c 0110 0114 0118 011c 0120 0124

pSomePointer = 0104

130

Computer Programming
6. Pointers and Arrays

De-referencing An Array Name


z

Using pointers can be faster than using array subscripts

Use a for loop to step through the array:


for(int i=0; i<SIZE; i++) {
cout << *(a + i) << endl;
}

131

Computer Programming
6. Pointers and Arrays

Relationship Between Pointers and Arrays


Arrays and pointers are closely related
Array name like a constant pointer
Pointers can do array subscripting operations
Example: Declare an array b[ 5 ] and a pointer bPtr

int b[5], *bPtr;


bPtr = b;
// To set them equal to one another
// The array name (b) is actually the address of first element of the array

bPtr = &b[ 0 ];
// Explicitly assigns bPtr to address of first element of b

To access element b[

3 ]:

x=*( bPtr + 3 )
x=bptr[ 3 ]

// Where n is the offset. Called pointer/offset notation

x=*( b + 3 )

// Performing pointer arithmetic on the array itself

// Called pointer/subscript notation


// bPtr[ 3 ] same as b[ 3 ]

132

Computer Programming
6. Pointers and Arrays

Relationship Between Pointers and Arrays

Pointers and arrays can be used interchangeably.


The array name is equivalent to the address of the first
element in the array

Example:
int a[10];
int *pa;
pa = &a[0]; /* is equivalent to pa = a */
So,
a[1]
*(pa+1)
pa[1] *(a+1)
&a[1]
pa+1
a+1
a[i]
*(pa+i)
pa[i] *(a+i)
&a[i]
pa+i
a+i
a[i]+=5 *(pa+i)+=5
pa[i]+=5
Example:
f(int s[])
f(int *s)
{
{
}
}

133

Computer Programming
6. Pointers and Arrays

Array of Pointers
So far the arrays are declared to store data in stack
Usually the memory space of stack is very small
If a large array is required, it is better to store the
elements of arrays in Free Store
In this case, for every element in an array, a pointer is
assigned to indicate its location in Free Store
This becomes an array of pointers.
The array itself is still in the stack.

134

Computer Programming
6. Pointers and Arrays

#include <iostream>
using namespace std;
class CAT
{public:
CAT() {itsAge = 1;}
~CAT() {}
Creating
Creating500
500CAT
CAT
int GetAge() const {return itsAge;}
objects
may
use
up
void SetAge(int age) {itsAge = age;}
objects may use upall
all
memory
in
the
stack
private:
memory in the stack
int itsAge;
Hence
};
Henceonly
onlyan
anarray
arrayof
of500
500pointers
pointersof
of
CAT
objects
are
created
in
the
stack
int main()
CAT objects are created in the stack
{
CAT *Family[500];
Each
int i;
EachCAT
CATobject
objectisislocated
locatedin
inthe
the
Free
Store
by
the
keyword
new
for (i=0; i<500; i++)
Free Store by the keyword new
{
Family[i] = new CAT;}
To
Family[255]->SetAge(1);
Toaccess
accessmember
memberof
ofaaparticular
particular
CAT
for (i=0; i<500; i++)
CATobject,
object,use
usethe
thecorresponding
corresponding
{
delete Family[i];
}
pointer
pointerin
inthe
thearray
array
return 0;
}

135

Computer Programming
6. Pointers and Arrays

Array of Pointers
CAT 2
(*Family[0])
CAT 0 CAT 1

Free Store
or
the heap
An
Anarray
arrayof
ofpointers
pointers
called
Family
called Familyisis
kept
keptto
topoint
pointto
to
different
elements
different elementsin
in
Free
Store
Free Store

CAT 499

...

The Stack
Code Space
Global Name Space

136

Computer Programming
6. Pointers and Arrays

Pointer of Array
If one feels that 500 pointers in the previous example are
still too many, we can put the whole array into Free Store
Hence one pointer is enough to point to the Array itself
but not an individual element
This becomes a pointer of array.

Family
Familyisisthe
thepointer
pointerof
of
array
and
points
to
array and points to
Family[0]
Family[0]in
inFree
FreeStore
Store

CAT *Family = new CAT[500];


int a = 0, b=0;
(Family+255)->SetAge(10);
a = (Family+255)->GetAge();// a = 10
b = Family[255].GetAge(); // b = 10
delete [] Family;

Individual
Individualelement
elementof
ofthe
the
array
of
the
CAT
objects
array of the CAT objects
can
canbe
beaccessed
accessedby
by
pointer
arithmetic
pointer arithmetic

137

Computer Programming
6. Pointers and Arrays

Pointer of Array
Family[0]

Family[499]

CAT 0 CAT 1

AApointer
pointerFamily
Familyisis
kept
keptto
topoint
pointto
tothe
the
beginning
memory
beginning memory
location
locationof
ofan
anarray
array
of
CAT
objects
of CAT objectsin
in
Free
Store
Free Store

...

CAT 499

Free Store
or
the heap

The Stack
Code Space
Global Name Space

138

Computer Programming
6. Pointers and Arrays

#include <iostream>
using namespace std;
class CAT
{public:
Arrays
Arrayscreated
createdin
inFree
Free
CAT() {itsAge = 1;}
Store
can
also
be
deleted
Store can also be deleted
~CAT(){;}
int GetAge() const {return itsAge;}
void SetAge(int age) {itsAge = age;}
private:
int itsAge;
};
int main()
{
CAT *Family = new CAT[10];
for (int i=0; i<10; i++)
{
Family[i].SetAge(2*i+1);
cout <<' '<< Family[i].GetAge();
}
The
The[]
[]symbol
symbolafter
afterdelete
delete
delete [] Family;
lets
the
system
know
the
return 0;
lets the system know the
whole
}
wholearray
arrayisisto
tobe
bedeleted
deleted

139

Computer Programming
6. Pointers and Arrays

Exercise 6.2
Based on the program in the last page, add a
destructor to CAT such that when it is called, the age
of the cat will be shown on the screen.
How many times the destructor will be called when
the delete [] Family; statement is executed?
Why?
What will happen if we use the statement delete
Family instead? Can it be executed in Visual C++?

140

Computer Programming
6. Pointers and Arrays

Exercise 6.2b
Modify the program in Ex.6.2 such that the Array
of Pointers approach is used to define the 10 objects
of CAT in the heap. Make sure your program will
not introduce memory leak.

141

Computer Programming
6. Pointers and Arrays

The
The null
null
character
character
String - char Arrays
represents
represents the
the
end
A string is an array of characters
end of
of string;
string; itit
must be
be added.
added.
A string can be simply initialized as follows: must
char Greeting[] =
Size of
{'H','e','l','l','o',' ','W','o','r','l','d','\0'}; array is 12

However, this method can easily introduce error


C++ provides a shorthand that makes use of the double
quote " ".
Totally
Totally12
12bytes
bytesare
are
allocated
for
Greeting.
allocated for Greeting.
Null
Nullcharacter
characterisis
automatically
automaticallygenerated.
generated.

char Greeting[] = {"Hello World"};

The braces can be removed

142

Computer Programming
6. Pointers and Arrays

C strings char arrays


z

char array will contain an extra null character


at the end of the string

Example:
char codes[] = sample;

115

97

109

112

108

101

608_01

144

Computer Programming
6. Pointers and Arrays

Character and C String


Characters and ASCII codes:
char x;
x = a; /* x = 97*/

Notes:
a and a are different; why?
a is the 97
a is an array of characters, { a, \0} or {97, 0}
a + b +c is invalid but a+b+c = ? (hint: a = 97 in ASCII)
a + b + c = 97 + 98 + 99 = 294 = 256 + 38 -> 38
in the memory

38

145

Computer Programming
6. Pointers and Arrays

Copying String
We often need to copy string from one character array to
another character array
char Greeting[12] = "Hello World";
char Greeting2[12];

Common errors:
Greeting2 = Greeting;

Wrong.
Wrong.Greeting2
Greeting2isisaaconstant
constantpointer;
pointer;we
wecannot
cannot
assign
assignanything
anythingto
toitit--See
Seeexplanation
explanationin
inthe
thenext
nextpage.
page.

146

Computer Programming
6. Pointers and Arrays

Greeting[12]
The Stack

'H' 'e' 'l'

Address

0100 0101 0102 0103

'l' 'd' '\0'


010a 010b 010c 010d

Greeting2[12]
The Stack
Address

0200 0201 0202 0203

Greeting2 = Greeting;

020a 020b 020c 010d

Wrong.
Wrong.We
Wetry
tryto
tomake
make
Greeting2
=
0101.
Greeting2 = 0101.However,
However,
Greeting2
Greeting2must
must==0201
0201as
asititisis
assigned
assignedby
bythe
theOS,
OS,and
andisisconstant
constant

147

Computer Programming
6. Pointers and Arrays

Greeting2[12] = Greeting[12];

th
Very
Verywrong.
wrong.Greeting2[12]
Greeting2[12]means
meansonly
onlythe
the13
13th
element
elementof
ofGreeting2,
Greeting2,not
notthe
thewhole
wholestring.
string.Besides,
Besides,
th
th
there
is
no
13
element
in
Greeting
or
Greeting2
there is no 13 element in Greeting or Greeting2

Note: Greeting2[11] = Greeting[11]; is valid, which


means assigning the 12th element of Greeting2 with the
value of the 12th element of Greeting.

148

Computer Programming
6. Pointers and Arrays

strcpy() and strncpy()

Warning: unsafe

C++ inherits from C a library of functions for tackling


strings
Two most common ones are strcpy() and strncpy()
#include <iostream>
State
Statethe
thedefinition
definitionof
ofstrcpy()
strcpy()
#include <cstring>
You
Youmay
mayomit
omitthis
thisline
linebecause
becauseitit
using namespace std;
isisalready
alreadyincluded
includedby
byiostream
iostream
int main()
{ char String1[] = {"Copy String1 to String2"};
char String2[80];
Copy
CopyString1
String1to
toString2
String2
strcpy(String2,String1);
cout << "String1: " << String1 << endl;
cout << "String2: " << String2 << endl;
return 0;
Result
Result
}

149

Computer Programming

Warning: unsafe
strcpy() will overwrite past the end of the destination if the
source were larger than the destination, damaging other data
6. Pointers and Arrays

To solve the problem, strncpy() can be used


#include <iostream>
#include <cstring>
State
Statethe
thedefinition
definitionof
ofstrncpy()
strncpy()
using namespace std;
int main()
{ const int MaxLength = 80; //MaxLength > strlen(String1) = 23
char String1[] = "Copy String1 to String2";
char String2[MaxLength+1]; //Initialize String2 if MaxLength<=23
strncpy(String2,String1,MaxLength);//String2 big enough
cout << "String1: " << String1 << endl;
cout << "String2: " << String2 << endl;
return 0;
Strncpy()
Strncpy()needs
needsanother
anotherparameter
parameter
}
MaxLength
MaxLengthwhich
whichspecifies
specifiesthe
themaximum
maximum

number
numberof
ofdata
data(not
(notincluding
includingnull)
null)to
tobe
becopied
copied

150

Computer Programming
6. Pointers and Arrays

Exercise 6.2c
a. Write a program that
creates an array of 3
objects of the class
ACCOUNT in the free
store. Pointer of array
b. Ask the user to input
three names and save
to each element of the
array
c. Read the content of
each element in the
array and display on
the screen.

class ACCOUNT
{
public:
void writename(char nm[]);
char * readname();
private:
char name[80];
};
void ACCOUNT::writename(char nm[])
{
strncpy(name,nm,79);
}
char * ACCOUNT::readname()
{
return name;
}

151

Computer Programming
6. Pointers and Arrays

String Conversion Functions


z

Conversion functions

In <cstdlib> (general utilities library)

Convert strings of digits to integer and floating-point


values

Prototype
double atof( const char *nPtr )

Description
Converts the string nPtr to double.

int atoi( const char *nPtr )

Converts the string nPtr to int.

long atol( const char *nPtr )

Converts the string nPtr to long int.

double strtod( const char *nPtr,


char **endPtr )
long strtol( const char *nPtr,
char **endPtr, int base )
unsigned long strtoul( const char
*nPtr, char **endPtr, int base )

Converts the string nPtr to double.


Converts the string nPtr to long.
Converts the string nPtr to unsigned
long.

152

Computer Programming
6. Pointers and Arrays

atoi and atol


atoi converts alphanumeric to int
z atol converts alphanumeric to long
int atoi(char *numericStr)
long atol(char *numericStr)
z Examples:
int number; long lnumber;
number = atoi("57");
lnumber = atol("50000");
z

153

Computer Programming
6. Pointers and Arrays

String Conversion Functions


atof
z

atof converts a numeric string to a


floating point number, actually a double

double atof(char *numericStr)


z Example:
double dnumber;
dnumber = atof("3.14159");

154

Computer Programming
6. Pointers and Arrays

A few more library functions


To measure the
length of a
string, the
function
Return
an int strlen() is
useful
To combine two
strings into one,
Append we can use the
a string function
strcat().

#include <iostream>
#include <cstring>
Convert
Convertan
an
using namespace std;
integer
integerinto
intoaa
int main()
string
{ char String1[100];
string
cout << "Please enter a word: ";
cin >> String1;
char String2[] = " has ";
Decimal radix
char String3[5];
char String4[] = " characters.";
itoa(strlen(String1),String3,10);
strcat(String1,String2);//ret String1
strcat(String1,String3);
strcat(String1,String4);
cout << String1 << endl;
return 0;
5 warnings
}

155

Computer Programming
6. Pointers and Arrays

A few more library functions


itoa
z
z
z

itoa converts an int to an alphanumeric string


Allows user to specify the base of conversion
itoa(int num, char *numStr, int base)
Example: To convert the number 1200 to a hexadecimal
string
char numStr[10];
itoa(1200, numStr, 16);
The function performs no bounds-checking on the array
numStr

156

Computer Programming
6. Pointers and Arrays

A few more library functions


strcat
strcat(char *dest, char *source)
z Takes two C-strings as input. It adds the contents of the
second string to the end of the first string:
char str1[15] = "Good ";
char str2[30] = "Morning!";
strcat(str1, str2);
cout << str1; // prints: Good Morning!
z No automatic bounds checking: programmer must ensure
that str1 has enough room for result

157

Computer Programming

Get one line of text (including


the spaces in between)

6. Pointers and Arrays

We can compare
if two strings are
the same using
the function
strcmp().
Syntax:
Syntax:
int
int strcmp(string1,
strcmp(string1,
string2)
string2)
Return
Return00ififstring1
string1isisthe
the
same
as
string2;
same as string2;otherwise
otherwise
returns
returnsaa+ve
+veor
orve
venumber.
number.

#include <iostream>
#include <cstring>
using namespace std;
No warning
int main()
{ char String1[100];
cout << "Please enter your name: ";
cin.getline(String1,100);
char String2[] = "Dr F Leung";
if (strcmp(String1, String2)==0)
cout << "Welcome Dr Leung.\n";
else
cout << "Login incorrect.\n";
return 0;
}

158

Computer Programming
6. Pointers and Arrays

A few more library functions


strcmp
int strcmp(char *str1, char*str2)
z
z

Compares strings stored at two addresses to determine


their relative alphabetic order:
Returns a value:
less than 0 if str1 precedes str2
equal to 0 if str1 equals str2
greater than 0 if str1 succeeds str2
if(strcmp(str1, str2) == 0)
cout << "equal";
else
cout << "not equal";

159

Computer Programming
6. Pointers and Arrays

Character Pointers
String constant acts like a character pointer
char *pc = ABCDE;

// declare a character pointer variable

Variable

Address

Value

constant
constant
constant
constant
constant
constant
pc

731
732
733
734
735
736
800

A
B
C
D
E
\0
731

731 A
732 B

800 731

733 C
734 D
735 E
736 \0

char s1[] = abc;


Variable

Address

Value

s1[0]
s1[1]
s1[2]
s1[3]

900
901
902
903

a
b
c
\0

160

Computer Programming
6. Pointers and Arrays

Arrays of Pointers
z Arrays

can contain pointers


z For example: an array of strings
char *suit[4] = {"Hearts", "Diamonds",
"Clubs", "Spades"};

Strings are pointers to the first character


char * each element of suit is a pointer to a char
The strings are not actually stored in the array suit, only pointers to
the strings are stored
suit[0]

\0

suit[1]

suit[2]

\0

suit[3]

\0

\0

suit array has a fixed size, but strings can be of any size

161

Computer Programming
6. Pointers and Arrays

Pointer Arrays
Syntax:
int *pi[3];
/* pi[0], pi[1], pi[2] */

float *pf[3];
/* pf[0], pf[1], pf[2] */

Example 2:

Example 1:

int i=1, j=2, k=3;


char *pc[3]={ABC, DEF, GH};
int *pi[3] = {&i, &j, &k};
Variable

Variable

Address

Value

80

82

84

pi[0]

100

80

pi[1]

101

82

pi[2]

102

84

constant
constant
constant
constant
constant
constant
constant
constant
constant
constant
Constant
pc[0]
pc[1]
pc[2]

Address

90
91
92
93
Const
94
can not 95
96
be
97
changed 98
99
100
200
202
204

Value

A
B
C
\0
D
E
F
\0
G
H
\0
90
94
98

162

Computer Programming
6. Pointers and Arrays

Dangers in using Functions from


<cstring>
z
z

z
z
z
z
z

There is a very real danger associated with the functions strcpy and
strcat.
Both these functions copy characters until a null character is found in
the source string, without regard to whether space is available in the
target.
If there is no space in the target, strcpy and strcat will happily
overwrite any variables in memory beyond the target array.
This may be some of your variables, or it could be something that your
system depends on to run correctly.
There could be a segmentation violation or illegal operation error, with
your program crashing, and no further problems.
The operating system could crash and burn.
Nothing apparent may happen. But the next application started could
crash and burn on loading. Be careful.

163

Computer Programming
6. Pointers and Arrays

The C++ Standard string class


z
z
z

z
z
z

The Standard Library supplied class string provides far more utility
than the cstrings C++ gets by way of its C heritage.
Class strings behave very much like built-in data types and are far
safer than cstrings.
Let s1, s2, and s3 be objects of class string, and suppose s1 and s2
have string values. Then + may be used for concatenation:
s3 = s1 + s2;
Additional space needed is allocated for s3 automatically.
The default constructor generates an empty string
There is a constructor that takes a cstring argument:
string phrase, word1(Hello ), word2(World);
phrase = word1 + word2;
cout << phrase << endl;
The output will be
Hello World

164

Computer Programming
6. Pointers and Arrays

The C++ Standard string class


z

Characteristic use of the getline function follow:

#include <iostream>
#include <string>
using namespace std;
//. . .
string str1;
getline(cin, str1);
//insert into str12 all input up to \n
//getline discards the \n
z
z

NOTE THAT class string objects do not range check index values.
If you want range checked indexing into strings, use the string member
function at(int_index).

str1.at(9); //Checks index value 9 for legality in str1.


//If legal,returns the character at index value 9.

165

Computer Programming
6. Pointers and Arrays

Command-Line Arguments
z

argc and argv

// int main( int argc, char* argv[ ])

In environments those support C++, there is a way to pass command-line


arguments or parameters to a program when it begin executing.
When main is called to begin execution, it is called with two arguments
argc and argv
z
z

argc : The first (conventionally called argc) is the number of command-line


arguments the program was invoked with
argv : The second (conventionally called argv) is a pointer to an array of
character strings that contain the arguments, one per string.

Example:

if echo is a program and executed on command prompt, such as


C:\> echo hello world
argv

pointer array
e c h o \0

argc
3

h e l l o \0
null

w o r l d \0

166

Computer Programming
6. Pointers and Arrays

Command-Line Processing
In many operating systems, command-line options are
allowed to input parameters to the program
SomeProgram Param1 Param2 Param3

e.g. ipconfig /all

To achieve this, main() allows two input parameters to


hold the command-line options.
int main(int argc, char *argv[])
{
return 0;
}

You can also write *argv[]


as **argv
The values of

argc
argcstores
storesthe
thenumber
number
of
parameters
of parameters

argv
argvisisan
anarray.
array.Each
Each argc and
element
elementof
ofthe
thearray
arrayisisaa argv[]are
provided indirectly
character
characterpointer
pointer

167

Computer Programming
6. Pointers and Arrays

Example
SomeProgram Param1 Param2 Param3
int main(int argc, char *argv[])
{
// function statements here
return 0;
}

main() is
inside the project
SomeProgram

argc
argc==44
argv[0]
argv[0]=="SomeProgram"
"SomeProgram"
argv[1]
argv[1] == "Param1"
"Param1"
argv[2]
=
"Param2"
argv[2] = "Param2"
argv[3]
argv[3] == "Param3"
"Param3"

i.e. argv[0][0] is 'S'

168

Computer Programming
6. Pointers and Arrays

Command-Line Processing

The program can


flow according to
the command line
options.

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
cout << "Received " << argc << " arguments." << endl;
for (int i = 0; i<argc; i++)
cout << "argument " << i << ": " << argv[i] << endl;
return 0;
}

Every
Everycommand
commandline
lineoptions
optionswill
willbe
beprinted
printedout
out

To add command-line options, this program must be run in


command-line, not Start Without Debugging.

169

Computer Programming
6. Pointers and Arrays

Exercise 6.2d
Build the program in the last page with the project name
Ex6p2d. Try to locate the executable file of the built
program using the Windows Explorer. Open a
Command Prompt to execute this program with the
following command line:
Ex6p2d aa bb param3 param4
What are shown on the screen?
Try to input different number of command-line options
to see the result.

170

Computer Programming
6. Pointers and Arrays

Exercise 6.2e
For the program in Ex6.2d, modify it such that a
warning message will be given if any two command-line
options are the same.

171

Computer Programming
6. Pointers and Arrays

Pass Parameters Pass by Value

To pass
parameters to
functions, we
may pass
parameters by
value, i.e. pass
copies of the
parameter
values to
functions.

#include <iostream>
using namespace std;
void swap(int x, int y)
{
int temp;
xxand
andyyare
areswapped
swapped
temp = x;
x=y;
only
onlyin
inswap()
swap()but
butnot
not
y=temp;
in
inmain()
main()
}
int main()
{
int x = 5, y = 10;
cout << "Main. Before swap, x: "
<< x << "y: " << y << "\n";
swap(x,y);
cout << "Main. After swap, x: "
<< x << " y: " << y << "\n";
return 0;
}

172

Computer Programming
6. Pointers and Arrays

x and y of main()
Variables

The stack
Address

x and y of swap()
x

pass-by-value
10

5 10
10
5

0100 0104 0108 010c 0110 0114 0118 011c 0120 0124

1.
4.
main()
returns
2.
swap()
is
called
3.
When
x
4.
When
swap()
returns
1.
At
main()
2.At
isswapped
called
3.
xand
andyyisis
swapped

temp = x;
x = y;
y = temp;

173

Computer Programming
6. Pointers and Arrays

Pass by Pointers
pointer
allows pass
parameters
by
reference.

#include <iostream>
using namespace std;
void swap(int *px, int *py)
{
int temp;
The
temp = *px;
Theaddresses
addressesof
ofxxand
and
*px=*py;
yyin
inmain()
main()are
arepassed
passed
*py=temp;
to
to swap()
swap()
}
int main()
{
int x = 5, y = 10;
cout << "Main. Before swap, x: "
<< x << " y: " << y << "\n";
swap(&x,&y);
cout << "Main. After swap, x: "
<< x << " y: " << y << "\n";
return 0;
}

174

Computer Programming
6. Pointers and Arrays

x and y of main()

px and py of swap()

Variables

px py

The stack
Address

5
10

510
5

0100 0104

0100 0104 0108 010c 0110 0114 0118 011c 0120 0124

pass-by-ref
1.
main()
3.
When
*px
and
*py
isis
2.
is
called
4.
1.
When
At
main()
swap()
3.
When
*px
andreturns
*py
2.At
is
called
4.
When
swap()
returns
swapped
swapped

temp = *px; //5


*px = *py; //10
*py = temp; //5

175

Computer Programming
6. Pointers and Arrays

Return Multiple Values


Normal function
can only return 1
value

If more than 1
values are to be
returned, it can
be done by
passing two or
more parameters
to a function by
reference.
sqr
sqrand
andcub
cubof
ofmain()
main()
are
arechanged
changedby
byopt()
opt()

#include <iostream>
using namespace std;
void opt(int, int *, int *); //prototype
int main()
{
int num, sqr, cub;
cout << "Input a number: ";
cin >> num;
opt(num, &sqr, &cub);
cout << "Square = " << sqr
<< endl;
cout << "Cube = " << cub << endl;
return 0;
}
void opt(int n, int *pS, int *pC)
{
*pS = n*n;
*pC = n*n*n;
}

176

Computer Programming
6. Pointers and Arrays

num, sqr and cub of main()


Variables num sqr cub
The stack

??
9 27
??
27

n, pS and pC of opt()
n

pS pC

3 0104 0108

Address 0100 0104 0108 010c 0110 0114 0118 011c 0120 0124
pass-by-value

pass-by-ref

4.
3.
*pS
opt()
and
returns
are
2.
1.
At
isreturns
called
4.
opt()
3.
When
*pS
and
*pC
are
2.
1.When
Atmain()
main()
is*pC
called
computed
computedin
inopt()
opt()

*pS = n*n;
*pC = n*n*n;

177

Computer Programming
6. Pointers and Arrays

Passing an array of parameters to a


name is a
function array
#include <iostream>
constant pointer
To save effort
from separately
passing a number
of parameters to a
function, they may
be passed as an
array.
string[]
string[]isisaacharacter
character
array,
so
string
array, so stringisisaa
character
characterpointer
pointer

#include <cstring>
using namespace std;
void opt(char * str);
int main()
{ char string[] =
{"This is a string"};
cout << string << endl;
opt(string);
cout << string << endl;
return 0;
function input
}

and output

void opt(char * str)


{ strcpy(str,"New String");
}

178

Computer Programming
6. Pointers and Arrays

Note that in the previous example, string is modified


inside the function opt()
It is because passing the name of an array is pass-byreference
When copying the string "New String" to str in
opt(), it is just the same as copying to the original
string.
string
and str are
the same
Result
Resultof
ofexecuting
executingthe
thelast
lastprogram
program

179

Computer Programming
6. Pointers and Arrays

Exercise 6.3
The following program defines a class CAT that contains a
private variable name[80]. A function is also defined. The
function will swap the name of two cats by using pointers.
Design the nameswap() function and the main() that will
(i) create & initialize the name of two cats as Frisky &
Felix in the stack.
(ii) show the initial name of the two cats created
(iii) swap the name of the two cats using the pointer
approach
(iv) show the name again.
Only swap the name, not the object

180

Computer Programming
6. Pointers and Arrays

Exercise 6.3 (Cont)


#include <iostream>
#include <cstring>
using namespace std;
class CAT
{public:
CAT(char * firstname) {strncpy(name,firstname,79);}
~CAT() {;}
char * GetName() {return name;}
void SetName(char *nameinput) {strncpy(name,nameinput,79);}
private:
char name[80];
};
void nameswap(CAT *CatA, CAT *CatB);

S-ar putea să vă placă și