Ch5-6 2014
Ch5-6 2014
Ch5-6 2014
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
Button
Variables (States)
Color = Grey
Size = 2cm x 2cm
Shape = Rectangular
(protruded)
Computer Programming
5. Basic Object Oriented Programming
Encapsulation
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
Method
Instantiation
Instance of
Button Class
Instantiation
Instance of
Button Class
Computer Programming
5. Basic Object Oriented Programming
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
z
z
z
Computer Programming
5. Basic Object Oriented Programming
Computer Programming
5. Basic Object Oriented Programming
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
11
Computer Programming
5. Basic Object Oriented Programming
Frisky.itsColor = 5;
12
Computer Programming
5. Basic Object Oriented Programming
13
Computer Programming
5. Basic Object Oriented Programming
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
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
16
Computer Programming
5. Basic Object Oriented Programming
// class TimeType
// class ComplexNumberType
. . .
17
Computer Programming
5. Basic Object Oriented Programming
Thats
Thatsthe
the
implementation
implementation
18
Computer Programming
5. Basic Object Oriented Programming
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
21
Computer Programming
5. Basic Object Oriented Programming
Class Constructors
z
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
24
Computer Programming
5. Basic Object Oriented Programming
Destructor
z
z
z
z
~Class ( );
Class :: ~Class ( )
25
Computer Programming
5. Basic Object Oriented Programming
Read only
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
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
32
Computer Programming
5. Basic Object Oriented Programming
Static Library
Header
library
33
Computer Programming
5. Basic Object Oriented Programming
CatClass.h
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
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
Yes
No
Yes
37
Computer Programming
5. Basic Object Oriented Programming
Click Dog?
Yes
No
Click Cat?
Yes
No
Click Sheep?
Yes
No
Click Horse?
Yes
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
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
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
42
Computer Programming
5. Basic Object Oriented Programming
43
Computer Programming
5. Basic Object Oriented Programming
specifications,
specifications,
you
youmay
may
design
designthe
the
above
class
above class
CAT
CAT
44
Computer Programming
5. Basic Object Oriented Programming
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
#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
47
Computer Programming
5. Basic Object Oriented Programming
48
Computer Programming
5. Basic Object Oriented Programming
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
51
Computer Programming
5. BasicObject
You Oriented
need toProgramming
enter the correct
Solution
Explorer
window
After
Afterbuilding
buildingthe
thelibrary,
library,the
theresult
resultisisshown
shown
52
Computer Programming
5. Basic Object Oriented Programming
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
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
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
#ifndef Preprocessor_Identifier
#define Preprocessor_Identifier
.
.
.
#endif
59
Computer Programming
5. Basic Object Oriented Programming
// timetype .cpp
// IMPLEMENTATION FILE
// client.cpp
// Appointment program
#include timetype.h
#include timetype.h
. . .
. . .
private:
. . .
. . .
};
#endif
60
Computer Programming
5. Basic Object Oriented Programming
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
61
Computer Programming
5. Basic Object Oriented Programming
2.
3.
4.
5.
62
Computer Programming
5. Basic Object Oriented Programming
If the user chooses (b), the 6-digit serial no. of the phone will be
shown on the screen
63
Computer Programming
5. Basic Object Oriented Programming
64
Computer Programming
6. Pointers and Arrays
65
Computer Programming
6. Pointers and Arrays
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
int b
30 0A 21 3A
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
67
Computer Programming
6. Pointers and Arrays
The
Theaddresses
addressesof
of
shortVar,
shortVar,
longVar
longVarand
and
sVar
sVar
68
Computer Programming
6. Pointers and Arrays
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
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
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!)
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
72
Computer Programming
6. Pointers and Arrays
What is a Pointer?
30 0A 21 3A
51
00
00 01
00
0100 0101 0102 0103 0104 0105 0106 0107 0108 0109
We
Wemodify
modifyaaindirectly
indirectlyby
by
using
usingits
itsaddress
address
73
Computer Programming
6. Pointers and Arrays
Pointers
z
z
z
//
A POINTER VARIABLE!!!!
p = &a;
74
Computer Programming
6. Pointers and Arrays
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)
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
81
Computer Programming
6. Pointers and Arrays
new operator
z
General form:
new type [num_elements]
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
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
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
86
Computer Programming
6. Pointers and Arrays
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
89
Computer Programming
6. Pointers and Arrays
// Initialize *pNum to 5
delete pNum;
pNum = 0;
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
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;
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
The object
The member
pointed by pCat function of the
object
Input parameter
of the member
function
97
Computer Programming
6. Pointers and Arrays
Pointers to Objects
z
z
z
z
->
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
Obj
Obj
4 bytes: count The Stack
Code Space
Global Name Space
100
Computer Programming
6. Pointers and Arrays
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
// Assume a = 0000
b = a + 1;
cout << "b = " << b << endl;
// b = 0002
// b - a = 1
102
Computer Programming
6. Pointers and Arrays
Holds address
103
Computer Programming
6. Pointers and Arrays
Pointers Arithmetic
The same applies to objects
Memory
Address
0000 0001 0002 0003 0004 0005 0006 0007 0008 0009
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
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
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
7000
99.4
temps[0]
7004
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
int
int
int
int
N = 20;
M = 40;
MaxStringSize = 80;
MaxListSize = 1000;
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
//wont work
8-113
114
Computer Programming
6. Pointers and Arrays
main()
myFunction()
myArray
115
Computer Programming
6. Pointers and Arrays
Use of const
z
116
Computer Programming
6. Pointers and Arrays
Passing An Array
}
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
int
int
temp[31] ;
numDays;
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
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
120
Computer Programming
6. Pointers and Arrays
121
Computer Programming
6. Pointers and Arrays
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
Base Address
8000
8048
8096
..
first row
second row
etc.
123
Computer Programming
6. Pointers and Arrays
124
Computer Programming
6. Pointers and Arrays
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
126
Computer Programming
6. Pointers and Arrays
const NUM_DEPTS
= 5;
const NUM_MONTHS = 12 ;
const NUM_STORES = 3 ;
5 DEPTS
rows
RE
O
ST eets
3 sh
12 MONTHS columns
127
Computer Programming
6. Pointers and Arrays
a,b;
SomeArray[5] = {10,20,30,40,50};
*SomeArray;
// a = 10
*(SomeArray+1); // b = 20, pointer arithmetic
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
129
Computer Programming
6. Pointers and Arrays
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
131
Computer Programming
6. Pointers and Arrays
bPtr = &b[ 0 ];
// Explicitly assigns bPtr to address of first element of b
To access element b[
3 ]:
x=*( bPtr + 3 )
x=bptr[ 3 ]
x=*( b + 3 )
132
Computer Programming
6. Pointers and Arrays
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
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
142
Computer Programming
6. Pointers and Arrays
Example:
char codes[] = sample;
115
97
109
112
108
101
608_01
144
Computer Programming
6. Pointers and Arrays
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
Address
Greeting2[12]
The Stack
Address
Greeting2 = Greeting;
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
148
Computer Programming
6. Pointers and Arrays
Warning: unsafe
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
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
Conversion functions
Prototype
double atof( const char *nPtr )
Description
Converts the string nPtr to double.
152
Computer Programming
6. Pointers and Arrays
153
Computer Programming
6. Pointers and Arrays
154
Computer Programming
6. Pointers and Arrays
#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
156
Computer Programming
6. Pointers and Arrays
157
Computer Programming
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
159
Computer Programming
6. Pointers and Arrays
Character Pointers
String constant acts like a character pointer
char *pc = ABCDE;
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
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
\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:
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
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
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
#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).
165
Computer Programming
6. Pointers and Arrays
Command-Line Arguments
z
Example:
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
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"
168
Computer Programming
6. Pointers and Arrays
Command-Line Processing
#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
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
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
175
Computer Programming
6. Pointers and Arrays
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
??
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
#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
178
Computer Programming
6. Pointers and Arrays
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