1 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. Color = Red Brand = Ferrari Speed = 200 mph Gear = 4 States Braking Accelerating Changing Gear Steering Behaviors Computer Programming Variables and functions 5. Basic Object Oriented Programming 2 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. Variables (States) Color = Grey Size = 2cm x 2cm Shape = Rectangular Method (Behavior) (protruded) Press( ) Computer Programming Button 5. Basic Object Oriented Programming
91
Embed
5. Basic Object Oriented Programming What is an Object?
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
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.
Color = Red Brand = Ferrari Speed = 200 mph
Gear = 4States
BrakingAccelerating
Changing Gear
Steering
Behaviors
Computer Programming
Variables and functions
5. Basic Object Oriented Programming
2
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.
Variables (States)Color = Grey
Size = 2cm x 2cm Shape = Rectangular
Method(Behavior)
(protruded)
Press( )
Computer Programming
Button
5. Basic Object Oriented Programming
3
Encapsulation• Hiding information within an object’s nucleus• Provide a public interface for interacting with it• Advantages to software developers
Modularity: An object can be easily passed aroundin the system (Otherwise, you need to think about how many files you need to bundle together to pass to your friends)
Information hiding: Users need not go into detailsof the object before using the object (E.g., you don’t need to know the circuit of a TV set if you want to watch TV)
Safety:Users of the object may not directly access the internal state of the object. This reduces the possibility of erroneous situations.
Computer Programming
Library Reusability
5. Basic Object Oriented Programming
4
Objects of class button
What is a Class?• A Class is a blueprint or prototype that defines
the variablesand methodscommon to all objects of a certain kind
• Every object of a Class is an instanceof that class• Benefit - Reusability
This arrangement saves effortin developing a number of objects of the same kind.
Usually objectsof a class are used many times in an application
• To declare a class, use the class keyword as follows
• Declaring this class doesNOT 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 Catwould do (by member functions, e.g.Meow() )
• Declaration of classes should be placed in the headerfile and included into your program.
Declaring Classes in C++
class Cat{
unsigned int itsAge; // Member variableunsigned int itsWeight; // Member variablevoid Meow(); // Member function
} ;
Computer Programming
#include
Definition of Meow() should follow somewhere
5. Basic Object Oriented Programming
9
• When a class is defined, we can further define the objectsof that class:Cat Frisky; // define one of the Cats call Frisky
• It states that we are going to handle a Cat called Frisky
• It is similar to declaring a number of the type integerint xyz; // define one of the integers call xyz
• Obviously, if one declares two cats as followsCat Frisky, Felix; // define two Cats
• Frisky is never the same as Felix , although they both belong to the class Cat , i.e. they are cats.
Exercise 5.2aBased on the program in page 15, write a program that will first print the age and weightof a cat called Felix , and then it asks the user to input the age and weightof that cat.
To do that, you need to do the following things:
a. Complete the implementation of the member functions GetWeight() and SetWeight() .
b. Add the main() function that prints the current statusof a cat Felix , then ask for user’s 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?
Computer Programming
Age and weight
5. Basic Object Oriented Programming
20
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)
• Besides constructor, every classhas also a destructor that will be called when the object of that class is destructed (removed).
Computer Programming
In memory
5. Basic Object Oriented Programming
21
Class Constructors
� a class constructor is a member function whose purpose is to initialize the private data members of a class object
� the name of a constructor is always the name of the class, and there is no return type for the constructor
� a class may have several constructors with different parameter lists. A constructor with no parameters is the default constructor
� a constructor is implicitly invoked when a class object is declared--if there are parameters, their values are listed in parentheses in the declaration
Constructors and Destructors• A possible main() function for the class Cat above is as
follows:// some lines of p.22// some lines of p.15int main(){ Cat Frisky(5) ;
Frisky.Meow();cout << "Frisky is a cat who is ";cout << Frisky.GetAge() << " years old.\n"; Frisky.Meow(); //Meow() does nothing hereFrisky.SetAge(7);cout << "Now Frisky is ";cout << Frisky.GetAge() << " years old.\n";Frisky.Meow();return 0;
}
A Cat Frisky is constructed hereThe constructor is called and the parameter 5is passed to the constructor and in turn initializes the private member variable itsAge to 5
Exercise 5.2cIdentify 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 coutusing namespace std;class Cat // begin declaration of the class{public: // begin public section
Cat(int initialAge); // constructor~Cat(); // destructorint GetAge() const; // accessor functionvoid SetAge(int Age); // accessor functionvoid Meow(); // general function
• The development of Object Oriented Programming has enabled a new business in software development
� People develop different classesand sell to other people
• These classes often provide functions that are popularly used in applications
� For example, the java calculator used in some Web pages
• People post the advertisement of their classes on the Web. Those who are interested in their classes can directly download it and perhaps pay by credit card.
Doing Business by Selling Classes5. Basic Object Oriented Programming
30
Computer Programming
• Assume that you have designed the following class CATand would like to sell it to a customer
#include <iostream> // for coutusing namespace std;class Cat // declare the class object{public: void SetAge (int age);
int GetAge();void SetWeight (int weight);int GetWeight();
private: int itsAge;int itsWeight;
};
• You do not want to give him the source codesof the member functions since your customer may copy your codes
• They may modify it and re-sell it to somebody else
• You do not want to give him the source codesof the member functions since your customer may copy your codes
• They may modify it and re-sell it to somebody else
int Cat::GetAge(){ return itsAge;}void Cat::SetAge(int age){ itsAge = age;}
5. Basic Object Oriented Programming
31
Computer Programming
• If the customer has the source code, he may try to modify it by himself
• It may introduce a lot of hidden errors as he knows very little about your program
• The resulting program can be very difficult to debug.
Conclusion: It is better to give your customer executable codessuch that they cannot reador modify it
Conclusion: It is better to give your customer executable codessuch that they cannot reador 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?
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?
5. Basic Object Oriented Programming
32
Computer Programming
Static Library• Rather than giving your customer the
executable codes, you can give him a (static) library
• Inside a library, it does not contain the executable codes, but the object codes– machine code waiting forlinking
• Since object codescannot be read directly, your customer cannot modify your codes
• To enable your customer know how to use your class, give also your customer a headerfile that contains the definition of your class.
Header
library
5. Basic Object Oriented Programming
33
Computer Programming
Main Program
main() of the Customer
#include "CatClass.h"
void main(){
CAT Frisky; Age = Frisky.GetAge();
}
MainProject.cpp
:
:
{
public:int GetAge();
};
CatClass.h
:
:
class CAT
Library
10 20 2d 35 5f 43 2343 23 …
… 22 6f… 21 44 dd 23
Contain the implementationof GetAge() , however, the source code
cannot be seen by the customer
Show that the class CAThas a public function
called GetAge()It will return an
integer
:
Explain why
public and private
When the customer build the main() , it
links with CatClass.h and the library
5. Basic Object Oriented Programming
34
Modular Program Design
Computer Programming
• 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 specificationsof each module, such as its functions, the calling methods, the parameters returned, are well defined
• Based on the specifications, the development of each module will be done by different programmers.
Very useful for teamwork
5. Basic Object Oriented Programming
35
Example– step 1: obtain the 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.
• The system analyst talks with the customer and obtains the following program requirements:
• Open a Win32 Console project, e.g. MainProject in the folder e.g. e:\VS_Proj\ENG236\Ch5\
• Enter the codes for the main() and other functions if necessary to implement the application
• Copy CatClass.h and LibCat.lib sent from the programmer to current folder e:\VS_Proj\ENG236\Ch5\MainProject\MainProject
• In Visual C++, click Project/ Add Existing Item...under MainProject . Select All Files to show all the files in the folder
• Add CatClass.h and LibCat.lib to the project
• Build Solution and run the application.
Prog.cpp
5. Basic Object Oriented Programming
55
Computer Programming
See the added CatClass.h and LibCat.lib here
See the added CatClass.h and LibCat.lib here
After building the application, the result is shown
After building the application, the result is shown
5. Basic Object Oriented Programming
56
Computer Programming
You may double-click LibCat.lib . You can only see some hex codes. No source codes can be found
You may double-click LibCat.lib . You can only see some hex codes. No source codes can be found
5. Basic Object Oriented Programming
57
Computer Programming
To see how to use the class CAT, double-click CatClass.hTo see how to use the class CAT, double-click CatClass.h
5. Basic Object Oriented Programming
58
� often several program files use the same header file containing typedef statements, constants, or class type declarations--but, it is a compile-time error to define the same identifier twice
� this preprocessor directive syntax is used to avoid the compilation error that would otherwise occur from multiple uses of #include for the same header file
Exercise 5.3 - Requirements• Write a program using Visual C++ to do the following:
• A class CATmust be created and your program will repeatedlyask user to choose one of the following
a. Set the weight of a catb. Get the weight of a catc. 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.
5. Basic Object Oriented Programming
61
Computer Programming
Exercise 5.3 (cont.) - Activity
1. Two students in a group. One plays the role of a System Analyst. One plays the role of a Programmer
2. The System Analystshould design the program structure using flow chart and define the specifications of the class required
3. The Programmer should develop the classand 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.
5. Basic Object Oriented Programming
62
Computer Programming
Exercise 5.3b - Requirements• Write a program using Visual C++ to do the following:
• A class PHONEmust be created and your program will repeatedly ask user to choose one of the following
a. Set the serial no. of a phoneb. Get the serial no. of a phonec. Ask the phone to ring!d. Quit
• If the user chooses (a), the user will be asked to input a 6-digit serial no. of the phone and the program will store it up
• If the user chooses (b), the 6-digit serial no. of the phone will be shown on the screen
• If user chooses (c), show the following message on the screen “ Ring ... Ring, Ring ... Ring ”
• If user chooses (d), quit the program.
5. Basic Object Oriented Programming
63
Exercise 5.3b (cont) - Activity
Computer Programming
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 Analystshould design the program structure using flow chart and define the specifications of the class required
3. The Programmer should develop the classand 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. Basic Object Oriented Programming
64
How memory is used in C++?
• The whole big piece of memory is divided into 4 areas:
Code Space - for the storage of program code
Stack - for the storage of local variables, passed parameters.
Global Name Space- for the storage of global variables
Free store- for the storage of dynamically createddata
int * pPointer;unsigned short int * pPointer2;pPointer = new int;:pPointer2 = new unsigned short int [2];:delete pPointer; // return it to systemdelete [] pPointer2; // return it to system
pPointer = 8004pPointer = 8004
pPointer2 = 8008pPointer2 = 8008
Computer Programming6. Pointers and Arrays
85
Null Address
� 0 is a constant pointer that represents the empty or null address
– Its value indicates that pointer is not pointing to any valid object
– Cannot dereference a pointer whose value is null
int *ptr = 0;
cout << *ptr << endl; // invalid, ptr
// does not point to
// a valid int
Computer Programming6. Pointers and Arrays
86
Dangling Pointers and Memory Leaks
� A pointer is dangling if it contains the address of memory that has been freed by a call to delete .– Solution: set such pointers to 0 as soon as memory
is freed.
� A memory leak occurs if no-longer-needed dynamic memory is not freed. The memory is unavailable for reuse within the program.– Solution: free up dynamic memory after use
10-86
Computer Programming6. 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;
delete [] A;
A
B0 1 2 3 4
A
B
Locations do not belong to program
—
?
Computer Programming6. Pointers and Arrays
Memory Leak
int *A = new int [5];
for (int i = 0; i < 5; ++i) A[i] = i;
A = new int [5];
A 0 1 2 3 4
— — — — —
These locations cannot be
accessed by program
A 0 1 2 3 4
Computer Programming6. Pointers and Arrays
89
Stray (Wild or Dangling) Pointers• When one deletes a pointer, the associated memorywill
be given backto system
• If one tries to use that pointer again without reassigningit, the result is unpredictable
• To ensure one will not use the deleted pointer again, always assign the pointer with the value 0 after delete
• A stray (or wild , dangling) pointer is the pointer that has been deleted but without assigning to null int *pNum = new int (5) ; // Initialize *pNum to 5
delete pNum;
pNum = 0; // To ensure the program will crash rather
// than unpredictable if one reuses it
Computer Programming6. Pointers and Arrays
NULLpoints to ROM
delete a pointer ≠ remove a pointer, it still exists
90
Exercise 6.1The 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:
Computer Programming6. Pointers and Arrays
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 newstatement 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
#include <iostream>using namespace std;int main(){ int localVariable = 5;
b = a + 1; // Don't touch *b as the memory is not from new
cout << "b = " << b << endl; // b = 0006
cout << "b - a = " << b-a << endl; // b - a = 1
Computer Programming6. Pointers and Arrays
You should not DIRECTLY assign a
value to a pointer, e.g.
int *p=0x00110110; �
104
Exercise 6.1bFind 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.
Exercise 6.1cModify 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 displaythem again.
d. After printing the age and weight of Felix , the program will repeatedlyask 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.
Computer Programming6. Pointers and Arrays
106
What Is an Array?• An array consists of a collectionof 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
int m = 4 ;temps[ 2 ] = 98.6 ;temps[ 3 ] = 101.2 ;temps[ 0 ] = 99.4 ;temps[ m ] = temps[ 3 ] / 2.0 ;
temps[0] temps[1] temps[2] temps[3] tem ps[4]
7000 7004 7008 7012 7016
99.4 ? 98.6 101.2 50.6
Computer Programming6. Pointers and Arrays
110
#include <iostream>using namespace std;int main(){ int myArray[5],i;
for (i=0; i< =5; i++)myArray[i] = 20;
for (i=0; i<5; i++)cout << myArray[i] << endl;
return 0;}
The kind of mistake people often make
Computer Programming6. Pointers and Arrays
No myArray[5] !!!Do not try to use myArray[5] ,result unpredictable
No myArray[5] !!!Do not try to use myArray[5] ,result unpredictable
111
Example more definitionsSuppose
const int N = 20;
const int M = 40;
const int MaxStringSize = 80;
const int MaxListSize = 1000;
Then the following are all correct array definitions
int A[10]; // array of 10 ints
char B[MaxStringSize]; // array of 80 chars
double C[M*N]; // array of 800 floats
int Values[MaxListSize]; // array of 1000 ints
Computer Programming6. Pointers and Arrays
112
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 itself to have 5 integers
AnotherArray requests the memory space in stack just enoughto hold the
data defined in the listBiggerArray declares itself to have 5 integers but only the first 2 of them are initialized. The others are 0.It is different from :
int IncorrectArray[2] = {10,20,30};
Computer Programming6. Pointers and Arrays
int a[5]; NOT the same as int a[5]={};
int BiggerArray[] = {10,20};
113
Copying One Array to Another
� Cannot copy with an assignment statement:tests2 = tests; //won’t work
� Must instead use a loop to copy element-by-element:
for (int i=0; i < SIZE; i++)
tests2[i] = tests[i];
8-113
Computer Programming6. Pointers and Arrays
114
Passing Arrays to FunctionsTo pass an array argument to a function, specify the name of the array
without any brackets int myArray[ 24 ];...
myFunction( myArray, 24 );...
Array size usually passed to function Arrays passed call-by-reference
� The called functions can modify the element values in the caller’s original array
� Name of array is the address of first element of the array� Function knows where the array is stored. Therefore, when the called
function modifies array elements in its function body, it is modifying the actual elements of array in the original memory locations
Pass array name
Size is also often sent as an argument
…myArray
main()
myFunction()
Computer Programming6. Pointers and Arrays
115
Use of const
� because the identifier of an array holds the base address of the array, an & is never needed for an array in the parameter list
� arrays are always passed by reference
� to prevent elements of an array used as an argument from being unintentionally changed by the function, you place const in the function heading and prototype
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 Call GetAge() of that CAT
Computer Programming6. Pointers and Arrays
119
Multi-dimensional Array• It is possible to have an array of more than 1 dimension
Two-dimensional arrayA Chess Board
int Board[8][8];
• A 2-dimensional array can be declared as
• Each element can be written or read as
Board[5][3] = 0;
int number = Board[5][3];
// number = 0
0 1 2 3 4 5 6 7
0
Computer Programming6. Pointers and Arrays
64 integers
120
Processing Two-Dimensional Arrays
� Two-dimensional arrays can be initialized in the declaration by listing values within braces, separated by commas – Braces can be used to distinguish rows, but are not
will be internally converted to x = SomeArray[0]; // x = 10
px = SomeArray; will be internally converted to
px = &(SomeArray[0]); // px = 0104
x = *SomeArray;
will be internally converted to x = SomeArray[0]; // x = 10
px = SomeArray; will be internally converted to
px = &(SomeArray[0]); // px = 0104
• There is NOT a memory location to store the pointer SomeArray . Everything is done by an internal conversion
129
Computer Programming6. Pointers and Arrays
A variable declared as a pointer can also be used as an arrayint 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 showncout << pSomePointer[2] << endl; // number 12 will be showncout << pSomePointer[3] << endl; // number 13 will be showncout << pSomePointer[4] << endl; // number 14 will be shown
The [] symbol after deletelets the system know the whole array is to be deleted
Computer Programming
139
Exercise 6.2
• Based on the program in the last page, add a destructor to CATsuch 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++?
Computer Programming6. Pointers and Arrays
140
Computer Programming6. 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 CATin the heap. Make sure your program will not introduce memory leak.
141
String - char Arrays • A string is an array of characters
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. Greeting2 is a constantpointer; we cannot assign anything to it -See explanation in the next page.Wrong. Greeting2 is a constantpointer; we cannot assign anything to it -See explanation in the next page.
146
Computer Programming6. Pointers and Arrays
0100 0101 0102 0103 010a 010b 010c 010dAddress
The Stack
Greeting[12]
'H' 'e' 'l' 'd' '\0''l'…
0200 0201 0202 0203 020a 020b 020c 010dAddress
The Stack ? ? ? ? ??…
Greeting2[12]
Greeting2 = Greeting;Wrong. We try to make Greeting2 = 0101. However, Greeting2 must = 0201 as it is assigned by the OS, and is constant
Wrong. We try to make Greeting2 = 0101. However, Greeting2 must = 0201 as it is assigned by the OS, and is constant
147
Computer Programming6. Pointers and Arrays
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
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
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 .
148
strcpy() and strncpy()• C++ inherits from C a library of functions for tackling
strings
• Two most common ones are strcpy() and strncpy()
#include <iostream>
#include <cstring>
using namespace std;
int main()
{ char String1[] = {"Copy String1 to String2"};
char String2[ 80];
strcpy(String2,String1);
cout << "String1: " << String1 << endl;
cout << "String2: " << String2 << endl;
return 0;
}
Copy String1 to String2
State the definition of strcpy()You may omit this line because it is already included by iostream
Computer Programming6. Pointers and Arrays
Result
Warning: unsafe
149
• 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>
Dangers in using Functions from <cstring>� There is a very real danger associated with the fun ctions strcpy and
strcat. � Both these functions copy characters until a null c haracter 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 strc at 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 applicati on started could
crash and burn on loading. Be careful.
6. Pointers and Arrays
Computer Programming
163
The C++ Standard string class � 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 t ypes 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 concaten ation:s3 = s1 + s2;
� Additional space needed is allocated for s3 automat ically.� The default constructor generates an empty string� There is a constructor that takes a cstring argumen t:
To add command-line options, this program must be run in command-line, not Start Without Debugging .
Every command line options will be printed out
The program can flow according to the command line options.
170
Exercise 6.2dBuild 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.
Computer Programming6. Pointers and Arrays
171
Computer Programming6. 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.
172
#include <iostream>using namespace std;void swap(int x, int y){ int temp;
temp = x;x=y;y=temp;
} 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; }
Pass Parameters – Pass by Value• To pass
parameters to functions, we may passparameters by value, i.e. pass copies of the parameter values to functions.
string[] is a character array, so string is a character pointer
string[] is a character array, so string is a character pointer
array name is a
constant pointer
function input
and output
180
Computer Programming6. 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 .
Result of executing the last programResult of executing the last program
stringand str are the same
181
Exercise 6.3
The following program defines a class CATthat 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 nameof the two cats using the pointer approach(iv) show the name again.