Class and Objects in C
Class and Objects in C
1
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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++
Button
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
6
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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++
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++
10
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Variables and
Accessing Class Members methods
13
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
cout << Frisky.itsAge << " years old.\n";
return 0;
}
14
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
21
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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::Meow()
{ cout << "Meow.\n";
} 25
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
26
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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++
29
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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++
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++
40
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
41
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
42
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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++
46
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
Solution
Explorer
window
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++
53
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
54
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
55
Computer Programming and Basic Software Engineering
5. Objects and Classes in C++
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
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;
}
Memory 30 0A 21 3A 51 44 20 00
Address 100 101 102 103 104 105 106 107 108 109
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
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
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
72
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;
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
Deleting Objects
Objects in the Free Store can also be deleted
Cat *pCat = new Cat;
delete pCat;
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
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
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
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
90
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
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
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};
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 .
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
97
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
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
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
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.
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
109
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
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;
111
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Greeting[12]
The Stack ? ? ? ? ? ?
Address 200 201 202 203 20a 20b 20c 20d
Greeting2[12] = Greeting[12];
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
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.
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
#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
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
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
124
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
125
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
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 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
128
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
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
string and
str are the
same
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
134