You are on page 1of 134

Writing a Good Program

5. Objects and Classes in C++

1
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

5.1 Basic Object Oriented


Programming

2
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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 = Blue
Brand = Ferrari
Changing Speed = 200 mph Steering
Gear Gear = 4
States

Accelerating Braking
Variables and functions
3
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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.

Button

Method Variables (States)


(Behavior) Color = Grey
Size = 2cm x 1.5cm
Press( ) Shape = Rectangular
(protruded)

4
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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
Library system (Otherwise, you need to think about how many
files you need to bundle together to pass to your
Reusability friends)
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.

5
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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

6
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

The Button Class

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

Instance of
Button Class
Instantiation

Instance of
Button Class

7
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

5.2 Objects and Classes in C++

8
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Declaring Classes in C++
To declare a class, use the class keyword
class Cat
{ P.12
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

9
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Declaring an Object of a Class


When a class is defined, we can further define the
objects of that class:
Cat Frisky; // declare 1 Cat object called 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; // declare 1 integer called xyz
Obviously, if one declares two cats as follows
Cat Frisky, Felix; // declare 2 Cat objects
Frisky is never the same as Felix, although they both
belong to the class Cat, i.e. they are cats.

10
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Variables and
Accessing Class Members methods

When an object is defined, we can access the members of


that object based on its class definition
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 and Basic Software Engineering
5. Objects and Classes in C++

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
P.9
12
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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 and Basic Software Engineering
5. Objects and Classes in C++

Private Versus Public


#include <iostream> // for cout
using namespace std;
class Cat // declare the class
{
int itsAge; An error is generated since by
int itsWeight; default itsWeight and itsAge
};
are private. They cannot be
int main() accessed even by 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 and Basic Software Engineering
5. Objects and Classes in C++

Private Versus Public


#include <iostream> // for cout
using namespace std;
class Cat // declare the class
{
public:
int itsAge;
Now itsWeight and itsAge are
int itsWeight;
}; public members. They can be
accessed by 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 and Basic Software Engineering
5. Objects and Classes in C++ P.18
How Private Variables Are Used?
#include <iostream> // for cout P.21
using namespace std;
class Cat // declare the class Cat
{
public: void SetAge (int age); Public
int GetAge(); Accessor
void SetWeight (int weight); Methods
int GetWeight(); Read/write
private: int itsAge;
Private member
int itsWeight;
};
variables
int Cat::GetAge()
{ return itsAge;
} Accessor methods provide
void Cat::SetAge(int age) access to private members
{ itsAge = age; since they are in the same
} class
16
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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:
int GetAge();
To indicate GetAge() is a
private: int itsAge; function of class Cat
};
Publicly known
int Cat::GetAge() Thats the Only the developer
{ return itsAge; knows
implementation
}
17
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
P.16 Ex 6.1c
Exercise 5.2a
Based on the program in page 16, 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. Do the following:
a. Complete the implementation of the member functions
GetWeight() and SetWeight().
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 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?
18
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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).
19
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
class Cat A typical Class definition with user-
{ defined constructor and destructor
public:
Cat(int initialAge); // Constructor of Cat
~Cat(); // Destructor of Cat
int GetAge(); Implementation of
void SetAge(int Age);
constructor: When any
void Meow(); //public function
object of the class Cat is
private:
constructed, this function
int itsAge;
};
is called and in effect it
will set itsAge to the
Cat::Cat (int initialAge)
{ itsAge = initialAge; parameter passed.
}
Cat::~Cat() Implementation of destructor: When
{ any object of the class Cat is
} destructed, this function is called
void Cat::Meow() {} which does nothing here.
20
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Constructors and Destructors
A possible main() function for the class Cat above is as
follows.
A Cat Frisky is constructed here.
// some lines of p.20 The constructor is called and the
// some lines of p.16 parameter 5 is passed to the
int main() constructor and in turn initializes the
{ Cat Frisky(5); private member variable itsAge to 5
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;
}

21
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

const Member Functions


It is possible that some functions will never
change the value of any member variable
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

22
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Ex 6.1c
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.

23
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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
};
24
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Cat::Cat(int initialAge) int main()
{ itsAge = initialAge; { Cat Frisky;
cout << "Cat Constructor\n"; Frisky.Meow();
} Frisky.Bark();
Frisky.itsAge = 7;
Cat::~Cat() return 0;
{ cout << "Cat Destructor\n"; }
}

int Cat::GetAge()
{ return (itsAge++);
}

void Cat::SetAge(int age)


{ itsAge = age;
}

void Cat::Meow()
{ cout << "Meow.\n";
} 25
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

5.3 Modular Programming with


C++

26
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Doing Business by Selling Classes


The development of Object Oriented
Programming has enabled a new business in
software development
Develop different classes and sell to other people
These classes often provide functions that are
popularly used in applications
E.g., 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.

27
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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 do not want to give him the
int itsWeight; source codes of the member
};
functions since your customer
int Cat::GetAge() may copy your codes
{ return itsAge;
} They may modify it and re-sell
void Cat::SetAge(int age) it to somebody else
{ itsAge = age;
} 28
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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: It is better to give your customer executable
codes such that they cannot read or modify it

Problem 1: A program without main() cannot be built; no


executable codes can be generated without main()
Problem 2: If your customer only has the executable codes,
how can he know the way to use your class?

29
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Rather than giving your customer the


Static executable codes, you can give him a
Library (static) library
Inside a library, it does not contain
the executable codes, but the object
Header codes machine code waiting for
linking
library
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.

30
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Explain why
CatClass.h
public and private
main() of the Customer
class CAT
Main Program Show that the
MainProject.cpp
{ : class CAT has
#include "CatClass.h" public:
int GetAge(); a public
void main()
: function called
{
GetAge()
: };
CAT Frisky;
It will return
Age = Frisky.GetAge(); an integer
: Library
}
10 20 2d 35 5f 43 23
Contain the
43 23 implementation
of GetAge(),
: however, the
source code
When the customer build the main(), it 22 6f cannot be seen
links with CatClass.h and the library 21 44 dd 23
by the
customer
31
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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 to team work


32
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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.

33
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Example
step 2: design the program flow
Based on the Start
requirements,
the system Draw animal
analyst
designs the No
All animal drawn?
program flow
using, for Yes
B
example, a
No
flow chart. User click on animal?

Yes
A
34
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Yes
A Click Dog? Play dog sound B
No
Yes
Click Cat? Play cat sound
No
Yes
Click Sheep? Play sheep sound
No
Yes
Click Horse? Play horse sound
No
Yes
Click End? End
No
35
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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
class DOG
public:
{ :
{ : int DrawShape();
class SHEEP
public:
public: int PlaySound(); { : int DrawShape();
int DrawShape(); : public:
int PlaySound();
int PlaySound(); };
int DrawShape(); :
: int PlaySound();
};
};
:
};

36
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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 it facilitates team work.
37
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Example
step 5: integrate the modules
DogClass.h
Integrating all modules by the system analyst
CatClass.h
class DOG
Main Program {
MainProject.cpp class CAT :
#include "DogClass.h" {
#include "CatClass.h" : public:
int DrawShape();
void main() public:
int PlaySound();
{ : int DrawShape();
int PlaySound(); :
DOG Bobby;
CAT Frisky; :
Bobby.DrawShape(); Library for};
DOG
Frisky.DrawShape(); Library for CAT };
: 10 20 2d 35 5f 43 23
43 23 10 20 2d 35 5f 43 23
Frisky.PlaySound(); 43 23
} :
: :
22 6f
Skeleton 21 44 dd 23 22 6f
21 44 dd 23
38
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Interface versus Implementation


A class stored in the header file is a contract
between the system analyst and programmers,
and between the developers and customers
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.
39
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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();

40
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Step 1: Create the class required


class CAT // declare the class
{
public: void SetAge (int age);
int GetAge();
private: int itsAge;
}; Based on the
specifications,
you may
design the
above class
CAT

41
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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() For each member


{ return itsAge; function, develop the
} required codes for
void CAT::SetAge(int age)
building the library
{ itsAge = age;
} Keep this restricted

42
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Step 3: Test the class


Create the header file and a main() for testing the
functionality of the class
This main() is only for testing purpose, NOT supposed to
be used in real application
MainTest.cpp
#include <iostream>
CatClass.h using namespace std;
class CAT
#include "CatClass.h"
{
// --- put implementation here
public: void SetAge (int age);
int main()
int GetAge();
{ CAT Frisky;
private: int itsAge;
Frisky.SetAge(7);
};
int Age = Frisky.GetAge();
cout << Age << endl;
return 0;
}
43
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Step 4: Create the library with Visual C++


Assume your class is fully tested. You can
create your library using Visual C++
Start your Visual C++ 2008
In Visual C++ 2008, start a new project as usual
Set the location to store your library project to, e.g.
e:\temp\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

44
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

45
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

In Visual C++ 2008 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

46
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Type your class declaration here


Remember to comment your codes
47
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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
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
48
Computer Programming and Basic Software Engineering
Need
5. Objects to enter
and Classes in C++the
correct path of the header file
It shows that the CatClass.h file is in the current
folder of the CatCodes.cpp file.

Solution
Explorer
window

After building the library, the result is shown


49
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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.

50
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

e:\temp
\ENG236
\Ch5\Li
bCat\
debug

e:\temp\ENG236\Ch
5\LibCat\LibCat

51
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Step 6: Integrating into the application
Open a Win32 Console Application, e.g.
MainProject in a folder e.g. e:\temp\ENG236\Ch5\
Enter the codes for 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:\temp\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.
52
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

After building the


application, the result is See the added
shown CatClass.h and
LibCat.lib here

53
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

You may double-click


LibCat.lib. You can only
see some hex codes. No
source codes can be found

54
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

To see how to use the class CAT,


double-click CatClass.h

55
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

Exercise 5.3 - Requirements


Using a Visual C++ program, 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.
56
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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.
57
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++ Not marked
Exercise 5.3b - Requirements
Using a Visual C++ program, 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. and the program will store it up
If the user chooses b, the 6-digit serial no. 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.
58
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++

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

59
Writing a Good Program
6. Pointers and Arrays

60
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

6.1 Pointers

61
Computer Programming and Basic Software Engineering
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/objects, passed parameters.
Global Name Space - for the storage of global
variables/objects
Free store - for the storage of dynamically
created data

62
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
73
How memory is used in C++?
main()
{ Statements;
funcA();
Statements;
funcB();
Statements;
} Free Store
funcA() or
{ int a; the heap
return;
}

funcB() The Stack


{ Cat Frisky; Code Space
return; Global Name Space
}
63
Computer Programming and Basic Software Engineering
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 Each variable has the
starting-byte address

Variables char a int b short int c bool d

Memory 30 0A 21 3A 51 44 20 00
Address 100 101 102 103 104 105 106 107 108 109

The character '0'


a: 30 Address of a = 0100 All values written in
hexadecimal but
b: 0A213A51 Address of b = 0101
binary in reality
c: 4420 Address of c = 0105
64
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

What is the Address of a Variable?


In C++, the symbol & indicates the address of a
variable #include <iostream>
using namespace std;
int main()
{ unsigned short shortVar = 5;
unsigned long longVar = 65535;
long sVar = -65535;
The addresses cout << "shortVar:\t" << shortVar;
of shortVar, cout << "\tAddress of shortVar:\t";
cout << &shortVar << "\n";
longVar and cout << "longVar:\t" << longVar;
sVar cout << "\tAddress of longVar:\t";
cout << &longVar << "\n";
cout << "sVar:\t\t" << sVar;
cout << "\tAddress of sVar:\t";
cout << &sVar << "\n";
return 0;
}
65
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

What is the Address of a Variable?


Variable and address of a variable are different

66
Computer Programming and Basic Software Engineering
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 int b (address of a) pa

Memory 10 0A 21 3A 51 00 00 01 00
Address 100 101 102 103 104 105 106 107 108 109
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 .
67
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

What is a Pointer?
In C++, each variable must have its type declared
int abc; // abc belongs to the type of integer
CAT Felix; // 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 good, as it does not tell the nature of a


How about (address of a character) pa;

Better, but look too clumsy


68
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

What is a Pointer? char *pa actually is declaring pa


C++ uses an elegant way to solve the problem
(but need some time to understand!)
It introduces a symbol * pa's content is an address,
the memory content of that
means the content of an address
address is a character
Variables char a int b char *pa

Memory 10 0A 21 3A 51 00 00 01 00
Address 100 101 102 103 104 105 106 107 108 109
char *pa states that the memory content of the address
stored in pa is a character. pa is indirectly declared to
be a variable storing an address of character.
69
Computer Programming and Basic Software Engineering
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 30 0A 21 3A 51 00 00 01 00
Address 100 101 102 103 104 105 106 107 108 109

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


cout << a; // a = '0' We modify a indirectly
pa = &a; // pa = 0100 by using its address
cout << *pa; // *pa = '0'
*pa = 49; // a = '1'
cout << a <<endl;
70
Computer Programming and Basic Software Engineering
6. Pointers
#include and Arrays
<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;
} 71
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

72
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Why Pointer? - Using Free Store 63


Pointer allows us to handle 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.
73
Computer Programming and Basic Software Engineering
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
unsigned short int * pPointer;
pPointer = new unsigned short int; in Free Store with size
: that is equal to an
// after using the memory space unsigned short integer
:
delete pPointer; // return it to system
We claim memory with
int * pPointer2; size equals to 2 integers.
pPointer2 = new int[2]; p.105 pPointer2 now points to
: the starting address of
// after using the memory space
this memory space
:
delete [] pPointer2; // return it to system
Results unpredictable if no []
74
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

int * pPointer;
unsigned short int * pPointer2; pPointer = 8004
pPointer = new int;
:
pPointer2 = new unsigned short int [2]; pPointer2=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

75
int *pNum = new int; is the same as
Computer Programming and Basic
int Software
*pNum; Engineering
6. Pointers and Arrays pNum = new int;

Stray (Wild or Dangling) Pointers


If one deletes a pointer, the associated memory
will be given back to system delete remove a pointer, it still exists
If one tries to use that pointer again without
NULL reassigning it, the result is unpredictable
points to To ensure one will not use the deleted pointer again,
ROM always assign the pointer with the value 0 after delete
A stray (or wild, dangling) pointer is one 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
76
Computer Programming and Basic Software Engineering
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 memory
claimed by both new statements in line 6 and line 11.

77
Computer Programming and Basic Software Engineering
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;
}

78
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Creating Objects in the Free Store


Similar to integer, we
can create objects in
the Free Store Size for a Cat object
Cat *pCat = new Cat;
pCat
pCat stores the Free Store
starting address of or
the memory allocated the heap
When the object is
created, its
constructor is called The Stack
Code Space
Object identified by a pointer. Global Name Space
79
Computer Programming and Basic Software Engineering
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.

80
Computer Programming and Basic Software Engineering
6. Pointers References and Arrays

#include <iostream>
using namespace std;
class SimpleCat Example
{
public:
SimpleCat(); The class
~SimpleCat();
int GetAge() const {return itsAge;}
SimpleCat
void SetAge(int age) {itsAge = age;}
private:
int itsAge;
};
SimpleCat::SimpleCat() Constructor
{ cout << "Constructor called.\n";
itsAge = 1;
}
SimpleCat::~SimpleCat()
{ cout << "Destructor called.\n"; Destructor
}
81
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
int main()
{
cout << "SimpleCat Frisky...\n";
SimpleCat Frisky;
cout << "SimpleCat *pRags = new SimpleCat...\n";
SimpleCat * pRags = new SimpleCat; pRags in the
cout << "delete pRags...\n";
delete pRags;
stack,
cout << "Exiting, watch Frisky go...\n"; *pRags in
return 0; the heap
}

Output of the
program

82
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Accessing Members of Objects


To access members of an object, the operator
(.) is used
SimpleCat *pCat = new SimpleCat;
(*pCat).SetAge(2);

The object The member Input parameter


The pointed by function of the of the member
Same pCat object function
In C++, a shorthand is provided for such
member access
SimpleCat *pCat = new SimpleCat;
pCat->SetAge(2); // The same as before

83
Computer Programming and Basic Software Engineering
6. Pointers
#include and Arrays
<iostream>
using namespace std;
class Object
{ Question
public:
Object();
~Object(); If I declare an
int GetCnt()
const {return *count;} object in the stack
private: that has member
int *count; variables in the
};
Object::Object() heap, what is in the
{ count = new int(1); stack and what is in
} // initialize *count to 1 the heap?
Object::~Object()
{ delete count;}
int main()
{ Object Obj;cout<<Obj.GetCnt()<<endl;
return 0;
} 84
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Answer
4 bytes on the stack
4 bytes: *count to hold Obj which
contains a pointer
count
Free Store
or 4 bytes on the heap
the heap that is pointed by
count of Obj
Obj
4 bytes: count The Stack
Code Space
Global Name Space
85
Computer Programming and Basic Software Engineering
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 10 0A 21 3A 51 44 20
Address 000 001 002 003 004 005 006 007 008 009

cout << "a = " << a << endl; // Assume a = 000


b = a + 1;
cout << "b = " << b << endl; // b = 002
cout << "b - a = " << b-a << endl; // b - a = 1

86
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
You should not DIRECTLY
Pointers Arithmetic assign a value to a pointer, e.g.
The same applies to objects int *p=0x00110110;
Variables Cat *a=new Cat; //Assume Cat object takes 6 bytes
Free Store
Memory
Address 001 002 003 004 005 006 007 008 009 010

Cat *a = new Cat;


Cat *b;
cout << "a = " << a << endl; // Assume a = 001
b = a + 1; // Don't touch *b as the memory is not from new
cout << "b = " << b << endl; // b = 007
cout << "b - a = " << b-a << endl; // b - a = 1
87
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Exercise 6.1b
Find out the errors in the following programs. Note
the error messages on building these program. Fix
the errors and rebuild it to verify your corrections.
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int *pInt; int SomeVariable = 5;
*pInt = 9; cout << "SomeVariable: "
cout << << SomeVariable << "\n";
"The value at pInt: " int *pVar = & SomeVariable;
<< *pInt << endl; pVar = 9;
return 0; cout << "SomeVariable: " <<
} *pVar << "\n";
return 0;
}
88
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
5.2a 5.2b
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.
89
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

6.2 Arrays and Strings

90
Computer Programming and Basic Software Engineering
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]; It states that there is a sequence of
25 short integer data. The whole
sequence is named as shortArray

Variables short shortArray[25]; //declaration

Memory
10 0A 21 3A ... .. 20 2A 4B 40
shortArray[0] shortArray[1] shortArray[24]

91
Computer Programming and Basic Software Engineering
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
: integers
shortArray[24] is the last element
NO shortArray[25] !!!
Do not try to use shortArray[25], result
unpredictable.

92
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

short shortArray[25]; Declaration

Variables short shortArray[25];

Memory
10 0A 21 3A ... .. 20 2A 4B 40
Address 009 00A 00B 00C ... ...037 038 039 03A
(Hex)
shortArray[0] = 0x100A;// 4106 in deciaml
shortArray[1] = 0x213A;// 8506 in decimal
:
shortArray[23] = 0x202A; Assignment
statements
shortArray[24] = 0x4B40;
93
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
NO myArray[5] !!!
#include <iostream> Do not try to use myArray[5],
using namespace std;
int main()
result unpredictable
{ int myArray[5],i;
for (i=0; i<=5; i++) The kind of mistake
myArray[i] = 20;
for (i=0; i<5; i++) people often make
cout << myArray[i] << endl;
return 0;
}

94
Computer Programming and Basic Software Engineering
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 declares AnotherArray takes the memory


itself to have 5 integers space in stack just enough to hold
the data defined in the list
BiggerArray declares itself to
have 5 integers but only the first int a[5]; NOT the same as
2 of them are initialized. The int a[5]={};
others are 0.
It is different from : int BiggerArray[] = {10,20};

int IncorrectArray[2] = {10,20,30};


95
Computer Programming and Basic Software Engineering
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 two-step 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 find out which CAT object Call GetAge() of that CAT object

96
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Multidimensional Array
It is possible to have an array of more than 1
dimension
A 2-dimensional array
can be declared as
0
int Board[8][8];
64 integers

Each element can be


written or read as
0 1 2 3 4 5 6 7
Board[5][3] = 0;
Two-dimensional array int number = Board[5][3];
A Chess Board // number = 0

97
Computer Programming and Basic Software Engineering
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};

4 4 4
3 7 2
2 4 6
1 1 2
0 0 0
0 1
98
Computer Programming and Basic Software Engineering
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 a,b;
int SomeArray[5] = {10,20,30,40,50};
a = *SomeArray; // a = 10
b = *(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 points to
the next element in the array

99
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

SomeArray[5]

The Stack 10 20 30 40 50
Address 100 104 108 10c 110 114 118 11c 120 124

There is NOT any memory location to store the pointer


SomeArray. Everything is done by an internal conversion
x = *SomeArray;
will be internally converted to
x = SomeArray[0]; // x = 10

px = SomeArray;
will be internally converted to
px = &(SomeArray[0]); // px = 104
100
Computer Programming and Basic Software Engineering
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]
SomeArray[5] pSomePointer
are the same.
The stack 10 11 12 13 14 104

Address 100 104 108 10c 110 114 118 11c 120 124

pSomePointer = 104
101
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Array of Pointers
So far the arrays are declared to store data in
the 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 the Free Store
In this case, for every element in an array, a pointer is
assigned to indicate its location in the Free Store
This becomes an array of pointers.

The array itself is still in the stack.

102
Computer Programming and Basic Software Engineering
#include 6.<iostream>
Pointers and Arrays
using namespace std;
class CAT
{public:
CAT() {itsAge = 1;} Creating 500 CAT
~CAT() {} objects may use up
int GetAge() const {return itsAge;} all memory in the
void SetAge(int age) {itsAge = age;} stack
private:
int itsAge;
}; Hence only an array of 500 pointers of
int main() CAT objects are created in the stack
{ CAT *Family[500];
int i; Each CAT object is located in
for (i=0; i<500; i++) the Free Store by new
{ Family[i] = new CAT;}
Family[255]->SetAge(3); To access the member of a
for (i=0; i<500; i++) particular CAT object, use the
{ delete Family[i];} corresponding pointer in the
return 0; array
}
103
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

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

Free Store
or
the heap
An array of CAT 499
pointers called
Family is kept to
... The Stack
point to different
elements in the Code Space
Free Store Global Name Space
104
Computer Programming and Basic Software Engineering
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 the Free Store
Hence one pointer is enough to point to the array itself
but not the individual element
It becomes a pointer of array. Family is the pointer of
array and points to
Family[0] in Free Store
CAT *Family = new CAT[500];
p.74 Individual element of
int a = 0, b=0; the array of the CAT
(Family+255)->SetAge(10); objects can also be
a = (Family+255)->GetAge();// a = 10 accessed by pointer
b = Family[255].GetAge(); // b = 10 arithmetic
delete [] Family;
105
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Pointer of Array

Family[0] Family[499]
CAT 0 CAT 1 ... CAT 499

Free Store
A pointer Family
or
is kept to point to the heap
the beginning
memory location
of an array of CAT The Stack
objects in Free Code Space
Store Global Name Space
106
Computer Programming and Basic Software Engineering
#include6. Pointers and Arrays
<iostream>
using namespace std;
class CAT
Arrays created in the
{public: Free Store can also
CAT() {itsAge = 1;} 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();
}
delete [] Family; The [] symbol after
return 0; delete lets the system
} know the whole array is
to be deleted 107
Computer Programming and Basic Software Engineering
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++?

108
Computer Programming and Basic Software Engineering
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.

109
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

The null character


String - char Array represents the end
of string; it must
A string is an array of characters be added.
A string can be simply initialized as follows:
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 12 bytes are
char Greeting[] = {"Hello World"}; allocated for Greeting.
Null character is
The braces can be removed automatically added.

110
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

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

Common errors:
Greeting2 = Greeting;

Wrong. Greeting2 is a constant pointer; we


cannot assign anything to it - See explanation
in the next page.

111
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Greeting[12]

The Stack 'H' 'e' 'l' 'l' 'd' '\0'


Address 100 101 102 103 10a 10b 10c 10d
Greeting2[12]

The Stack ? ? ? ? ? ?
Address 200 201 202 203 20a 20b 20c 20d

Wrong. We try to make Greeting2


Greeting2 = Greeting; = 101. However, Greeting2 must =
201 as it is assigned by the OS,
and is constant
112
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Greeting2[12] = Greeting[12];

Very wrong. Greeting2[12] means only the 13th


element of Greeting2, not the whole string.
Besides, there is NO 13th 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; NOT copying the whole string.

113
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Warning: unsafe
strcpy() and strncpy()
C++ inherits from C a library of functions for
tackling strings
Two most common ones are strcpy() and strncpy()
#include <iostream> State the definition of strcpy()
#include <string.h>
using namespace std; You may omit this line because it is
int main() already included by iostream
{ char String1[] = {"Copy String1 to String2"};
char String2[80]; Copy String1 to String2
strcpy(String2,String1);
cout << "String1: " << String1 << endl;
cout << "String2: " << String2 << endl;
return 0;
}
Result

114
Computer Programming and Basic Software Engineering
6. Pointers and Arrays Warning: unsafe
Strcpy() will overwrite past the end of the
destination if the source were larger than the
destination, damaging other data
To solve the problem, strncpy() can be used
#include <iostream>
#include <string.h> State the definition of 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() needs another parameter MaxLength
} which specifies the maximum number of data
(not including '\0') to be copied 115
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
A few more library functions
To measure the #include <iostream>
length of a #include <string.h> Convert an
string, the using namespace std; integer into a
function int main() string
Return a strlen() is { char String1[100];
number useful cout << "Please enter a word: ";
cin >> String1;
To combine two char String2[] = " has ";
strings into one, Set decimal
char String3[5];
we can use the char String4[] = " characters.";
function itoa(strlen(String1),String3,10);
Append strcat().
a string strcat(String1,String2);//ret String1
strcat(String1,String3);
strcat(String1,String4);
cout << String1 << endl;
return 0;
5 warnings
} 116
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Get one line of text (including
We can compare the spaces in between)
if two strings are #include <iostream>
No warning
the same using #include <string.h>
using namespace std;
the function int main()
strcmp(). Including '\0'
{ char String1[100];
Syntax: cout << "Please enter your name: ";
int strcmp(string1, cin.getline(String1,100);
string2) char String2[] = "Dr F Leung";
Return 0 if string1 is if (strcmp(String1, String2)==0)
the same as string2; cout << "Welcome Dr Leung.\n";
otherwise returns a else
positive or negative cout << "Login incorrect.\n";
return 0;
number.
}

117
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Exercise 6.2c class ACCOUNT


a. Write a program that {
public:
creates an array of 3
void writename(char nm[]);
objects of the class char * readname();
ACCOUNT in the free private:
store. Pointer of array char name[80];
b. Ask the user to input };
three names and save
void ACCOUNT::writename(char nm[])
to each element of {
the array strncpy(name,nm,79);
c. Read the content of }
each element in the
char * ACCOUNT::readname()
array and display on
{
the screen. return name;
}

118
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Command-Line Processing
In many operating systems, command-line
options are allowed to input parameters to the
program
e.g. ipconfig /all
SomeProgram Param1 Param2 Param3
To achieve this, main() allows two input parameters
to hold the command-line options.

int main(int argc, char *argv[]) You can also write


{ return 0; *argv[] as **argv
}
The values of
argc stores the argv is an array. Each argc, argv[]are
number of parameters element of the array assigned
is a character pointer automatially
119
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

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

argc = 4
argv[0] = "SomeProgram"
i.e. argv[0][0] is 'S'
argv[1] = "Param1"
argv[2] = "Param2"
argv[3] = "Param3"

120
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Command-Line Processing The program


flows 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 command line options will be printed out

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


in command-line, NOT Start Without Debugging.

121
Computer Programming and Basic Software Engineering
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.
122
Computer Programming and Basic Software Engineering
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.

123
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

6.3 Parameter passing using


pointers

124
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Pass Parameters Pass by Value


To pass #include <iostream>
parameters using namespace std;
void swap(int x, int y)
to functions, { int temp;
we may pass x and y are swapped
temp = x;
only in swap() but not
parameters x=y;
in main()
y=temp;
by value, i.e. }
pass copies int main()
of the { int x = 5, y = 10;
cout << "Main. Before swap, x: "
parameter << x << "y: " << y << "\n";
values to swap(x,y);
functions. cout << "Main. After swap, x: "
<< x << " y: " << y << "\n";
return 0; }

125
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

x and y of main() x and y of swap()

x y x y
Variables
pass-by-value

The stack 5 10 10 5
5 10
Address 100 104 108 10c 110 114 118 11c 120 124

temp = x;
x = y;
1. When
3.
2.
4. At main()
When x and y is
swap()
swap() returns
swapped
called y = temp;

126
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Pass by Reference
#include <iostream>
using namespace std;
void swap(int *px, int *py)
Pointer { int temp;
allows pass temp = *px; The addresses of x and
*px=*py; y in main() are passed
parameters *py=temp; to swap()
by }
reference. 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;
}
127
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

x and y of main() px and py of swap()

x y px py
Variables

The stack 10
5 10
5 100 104

Address 100 104 108 10c 110 114 118 11c 120 124
pass-by-ref

temp = *px; //5


4. When
1.
2.
3. At main()
*px andreturns
swap() is*py
called
is *px = *py; //10
swapped *py = temp; //5

128
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Return Multiple Values


Normal function #include <iostream>
using namespace std;
can only return void opt(int, int *, int *); //prototype
1 value int main()
If more than 1 { int num, sqr, cub;
cout << "Input a number: ";
value are to be cin >> num;
returned, it can opt(num, &sqr, &cub);
be done by cout << "Square = " << sqr
passing 2 or << endl;
more cout << "Cube = " << cub << endl;
parameters to a return 0;
function by }
reference. void opt(int n, int *pS, int *pC)
{
sqr and cub of main() *pS = n*n;
are changed by opt() *pC = n*n*n;
}
129
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

num, sqr and cub of main() n, pS and pC of opt()

n pS pC
Variables num sqr cub

The stack 3 9 27
?? ?? 3 104 108
Address 100 104 108 10c 110 114 118 11c 120 124
pass-by-value pass-by-ref

4.
2.
3.
1. When
At main()
*pS and
opt() is *pC
returns
called *pS = n*n;
*pC = n*n*n;
are computed in opt()

130
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Passing an array of parameters to a


function array name is a
constant pointer
#include <iostream>
#include <string.h>
To save effort from using namespace std;
void opt(char * str);
separately passing int main()
a number of { char string[] =
parameters to a {"This is a string"};
cout << string << endl;
function, they may opt(string);
be passed as an cout << string << endl;
array. return 0;
function input
}
string[] is a character and output
array, so string is a void opt(char * str)
character pointer { strcpy(str,"New String");
}
131
Computer Programming and Basic Software Engineering
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-by-
reference
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 of executing the last program

132
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Exercise 6.3
The following program defines a class CAT that
contains a private variable name[80]. A function
that swaps the name of two cats by using pointers
is also defined. Design the nameswap() function
and the main() that will
1. Create and initialize the name of two cats as Frisky
and Felix in the stack.
2. Show the initial name of the two cats created
3. Swap the name of the two cats using the pointer
approach Only swap the name, not the object
4. Show the name again.

133
Computer Programming and Basic Software Engineering
6. Pointers and Arrays

Exercise 6.3 (Cont)


#include <iostream>
#include <string>
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);

134

You might also like