Introduction to Object-oriented Programming Introduction to Object-oriented Programming CMPS 2143.
5. Basic Object Oriented Programming What is an Object?
Transcript of 5. Basic Object Oriented Programming What is an Object?
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
Computer Programming5. Basic Object Oriented Programming
5
VariablesColor (e.g. Grey )
Size (e.g. 2cm x 2cm )Shape (e.g. Rectangular )
(protruded)
Method
The Button Class
Instance of Button Class
Instance of Button Class
Instantiation
Instantiation
Press( )
Computer Programming5. Basic Object Oriented Programming
Attributes:AgeHeightWeight
Methods:Move
Attributes:AgeHeightWeight
Methods:Move
PersonPerson
Class
larrylarry
Attributes:Age = 54Height = 179 cmWeight = 67 kg
Methods:Move
Attributes:Age = 54Height = 179 cmWeight = 67 kg
Methods:Move
billbill
Attributes:Age = 47Height = 177 cmWeight = 68 kg
Methods:Move
Attributes:Age = 47Height = 177 cmWeight = 68 kg
Methods:Move
scottscott
Attributes:Age = 52Height = 182 cmWeight = 75kg
Methods:Move
Attributes:Age = 52Height = 182 cmWeight = 75kg
Methods:Move
stevesteve
Attributes:Age = 50Height = 180 cmWeight = 71 kg
Methods:Move
Attributes:Age = 50Height = 180 cmWeight = 71 kg
Methods:Move
Instances
Many Different Objects from a Single Class
Computer Programming5. Basic Object Oriented Programming
6
7
Classes are implementations of Data Types
� A class is a programmer-defined data type and objects are variables of that type
– Just like in int x; , x is a variable of type int
� Class : in some sense, a data type that defines both data and functions
� When a data type has been created, programmers can use it without knowing how it is implemented internally
� Example: a date object might include operations for various display formats, comparing two dates, extracting the month, day, and year numbers, etc.
� A class generally contains private data and public operations (called member functions)
Computer Programming5. Basic Object Oriented Programming
8
• 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.
Declaring an Object of a Class
Computer Programming5. Basic Object Oriented Programming
10
• When an object is defined, we can access the members of that object based on its class definition
• For example, if we want to know the weight of Frisky :unsigned int weight = Frisky . itsWeight;
// Get the weight of Frisky
• The operator ‘. ’ allows us to access the members of the object
• Similarly, if we want to know the age of Frisky :unsigned int age = Frisky.itsAge;
// Get the age of Frisky
• If we want to ask Frisky to meow:Frisky.Meow(); // Ask Frisky to execute meow()
Accessing Class Members
Computer Programming
Variable and methods
5. Basic Object Oriented Programming
11
• Never access directly to class
Cat.itsAge = 5; // Don’t do that! Cat is class
• It is because Cat is only a template of all cats. A different cat may have a different age
• If we want to assign the age of Frisky , we write:
Frisky.itsAge = 5; // Set the age of Frisky to 5
• Also, if the class doesn’t define a member, you can’t use it
Frisky.bark(); // Frisky has no bark() defined
Frisky.itsColor = 5; // Also error, because the class
// Cat does not have itsColor
Accessing Class Members
Computer Programming5. Basic Object Oriented Programming
12
• Members can be divided into public members or privatemembers
• Private members of a class are those members that can only be accessed by methods of that class
• By default, all members are private
• Public members of a class are those members that can be accessed by other class objects and functions
• This mechanism provides the privacy or security to the information of a class that requires protection.
Private Versus Public
Computer Programming
Typically, access private members by public methods.
5. Basic Object Oriented Programming
13
#include <iostream> // for coutusing namespace std;class Cat // declare the class {
int itsAge;int itsWeight;
};
int main(){
Cat Frisky;Frisky.itsAge = 5; // assign to the member variablecout << "Frisky is a cat who is ";cout << Frisky.itsAge << " years old.\n";return 0;
}
Private Versus Public
An error is generated since by default itsWeight and itsAge
are private. They cannot be accessed even by main()
Computer Programming5. Basic Object Oriented Programming
14
Private Versus Public#include <iostream> // for coutusing namespace std;class Cat // declare the class{public:
int itsAge;int itsWeight;
};
int main(){
Cat Frisky;Frisky.itsAge = 5; // assign to the member variablecout << "Frisky is a cat who is ";cout << Frisky.itsAge << " years old.\n";return 0;
}
Now itsWeight and itsAgeare public members. They can
be accessed by main()
Computer Programming5. Basic Object Oriented Programming
15
How Private Variables are used?#include <iostream> // for coutusing namespace std;class Cat // declare the class Cat{public: void SetAge (int age);
int GetAge();void SetWeight (int weight);int GetWeight();
private: int itsAge;int itsWeight;
};int Cat :: GetAge(){ return itsAge;}void Cat::SetAge(int age){ itsAge = age;}
Public Accessor Methods
Accessor methods provide access to private members since they are in the same class
Computer Programming
Read/write
Private member variables
5. Basic Object Oriented Programming
16
Scope Resolution Operator ( :: ) � C++ programs typically use several class types
� different classes can have member functions with th e same identifier, like Write( )
� member selection operator is used to determine the class whose member function Write( ) is invoked
currentTime .Write( ) ; // class TimeTypenumberZ .Write( ) ; // class ComplexNumberType
� in the implementation file, the scope resolution op erator is used in the heading before the function member’s name to sp ecify its class
void TimeType :: Write ( ){ . . .
}
Computer Programming5. Basic Object Oriented Programming
17
Implementing Class Methods• Member functions declared in a class are only prototypes
of these functions
• Actual implementation (the operations performed by the function) should be separatelydescribed.
#include <iostream> // for coutusing namespace std;class Cat // declare the class Cat{public:
int GetAge();private: int itsAge;};
int Cat :: GetAge(){ return itsAge;}
To indicate GetAge() is a function of class Cat
That’s the implementation
Computer Programming
Publicly known
Only the developer
knows
5. Basic Object Oriented Programming
18
Two Separate Files used// SPECIFICATION FILE ( timetype .h )// Specifies the data and function members.class TimeType{
public:. . .
private:. . .
} ;
// IMPLEMENTATION FILE ( timetype.cpp )// Implements the TimeType member functions.
. . .
Computer Programming5. Basic Object Oriented Programming
19
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
Computer Programming5. Basic Object Oriented Programming
22
class Cat{public:
Cat(int initialAge); // Constructor of Cat~Cat(); // Destructor of Catint GetAge();void SetAge(int Age);void Meow(); //public function
private:int itsAge;
};Cat::Cat (int initialAge){ itsAge = initialAge;}Cat::~Cat(){}void Cat::Meow() {}
A typical Class definition with user-definedconstructor and destructor
Implementation of constructor
When any object of the class Cat is constructed, this function is called and in
effect it will set itsAge to the parameter passed
Implementation of destructorWhen any object of the class Cat is
destructed, this function is called which in effect does nothing
Computer Programming5. Basic Object Oriented Programming
23
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
Computer Programming5. Basic Object Oriented Programming
24
Destructor
� Member function automatically called when object goes out of scope
� Name of destructor function required to be class name preceded by tilde (~)
� Cannot return a value or contain arguments� General destructor declaration:
~Class ( );Class :: ~Class ( )
Declaration in class definition
Declaration in function definition
Computer Programming5. Basic Object Oriented Programming
25
• It is possible that some functions will never change the value of any member
• It is desirable to declare them as const member function
• Then, the compiler will automatically check if there is any inconsistencyin the program
• It helps to debugthe program
• In the example above, obviously GetAge() and GetWeight() will not change any member
• Hence they can be declared as const as follows:int GetAge() const ; // add the keyword const when
int GetWeight() const; // you declare the functions
const Member Functions
Computer Programming
Read only
5. Basic Object Oriented Programming
26
Exercise 5.2b
From the program you wrote in exercise 5.2a
a. Add the constructor and destructor such that the initial ageand 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.
Computer Programming5. Basic Object Oriented Programming
27
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
private:int itsAge; // member variable
};
Computer Programming5. Basic Object Oriented Programming
28
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;
}
Computer Programming5. Basic Object Oriented Programming
29
Computer Programming
• 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:
Computer Programming5. Basic Object Oriented Programming
36
Example– step 2: design the program flow
Computer Programming
• Based on the requirements, the system analyst designs the program flowusing, for example, a flow chart.
Start
All animal drawn?
User click on animal?
No
Yes
A
No
Yes
B
Draw animal
5. Basic Object Oriented Programming
37
Computer Programming
A Click Dog?
Click Cat?
Click Sheep?
Click Horse?
Click End?
BPlay dog sound
Play cat sound
Play sheep sound
Play horse sound
End
Yes
Yes
Yes
Yes
Yes
No
No
No
No
No
5. Basic Object Oriented Programming
38
Computer Programming
Example– step 3: divide into modules
• From the flow chart, identify the classes required and their functions
{
public:int DrawShape();int PlaySound();
};
DogClass.h
:
:
class DOG{
public:int DrawShape();int PlaySound();
};
CatClass.h
:
:
class CAT
{
public:int DrawShape();int PlaySound();
};
SheepClass.h
:
:
class SHEEP{
public:int DrawShape();int PlaySound();
};
HorseClass.h
:
:
class HORSE
5. Basic Object Oriented Programming
39
Computer 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.
5. Basic Object Oriented Programming
40
Example– step 5: integrate the modules
{
public:int DrawShape();int PlaySound();
DogClass.h
:class CAT
};:
Computer Programming
Main Program
Integrating all modules by the system analyst
#include “DogClass.h"
void main(){
DOG Bobby; CAT Frisky; Bobby.DrawShape();Frisky.DrawShape();
}
MainProject.cpp
:
:Frisky.PlaySound();
:
#include “CatClass.h" {
public:int DrawShape();int PlaySound();
CatClass.h
:class CAT
Library for CAT
10 20 2d 35 5f 43 2343 23 …
… 22 6f… 21 44 dd 23
:
};:
Library for DOG
10 20 2d 35 5f 43 2343 23 …
… 22 6f… 21 44 dd 23
:
:
Skeleton
5. Basic Object Oriented Programming
41
Interface versus Implementation• The declaration of a classstored in the header file is in fact
a contract between the System Analyst and Programmer, and between the developer and customer
• System Analyst who wants to use the object of this class should follow the rules defined in the declaration
• Class should be implemented exactly the same way it is declared; otherwise the customer using it will have error
• C++ is strongly typed, i.e., the compiler will enforce the contracts and set the error flag if someone violates them
• In the language of OO programming, this contract is named as interface.
Computer Programming5. Basic Object Oriented Programming
42
Computer Programming
Create a static library with Visual C++• Suppose you are one of the programmers and is asked to
develop the class CAT
• Now, the system analyst sets out two specificationson the class CAT:
1. It should have a function that allows the setting of CAT’s age. The function is
void SetAge(int age);
2. It should have another function that allows the reading of CAT’s age. The function is
int GetAge();
5. Basic Object Oriented Programming
43
Computer Programming
Step 1: Create the class required
class CAT // declare the class{public: void SetAge (int age);
int GetAge();private: int itsAge;}; • Based on the
specifications, you may design the above class CAT
• Based on the specifications, you may design the above class CAT
5. Basic Object Oriented Programming
44
Computer Programming
Step 2: Implement the classclass CAT // declare the class{public: void SetAge (int age);
int GetAge();private: int itsAge;};
int CAT::GetAge(){ return itsAge;}void CAT::SetAge(int age){ itsAge = age;}
• For each member function, develop the required codes for building the library
• Keep this restricted
• For each member function, develop the required codes for building the library
• Keep this restricted
To be put to header file
5. Basic Object Oriented Programming
45
Computer Programming
Step 3: Test the class
class CAT{public: void SetAge (int age);
int GetAge();private: int itsAge;};
• Create the header fileand a main() for testing the functionality of the class
• This main() is only for testing purpose, not supposed to be used in real application
• Create the header fileand a main() for testing the functionality of the class
• This main() is only for testing purpose, not supposed to be used in real application
#include <iostream>using namespace std;#include "CatClass.h"// --- put implementation hereint main(){ CAT Frisky;
Frisky.SetAge(7);int Age = Frisky.GetAge();cout << Age << endl;return 0;
}
CatClass.hMainTest.cpp
5. Basic Object Oriented Programming
46
Step 4: Create library with Visual C++
Computer Programming
• Assume your class is fully tested. You can create your library using Visual C++
• Start your Visual C++ 2017
• In Visual C++ 2017, start a new project as usual
• Set the location to store your library project to, e.g. e:\VS_Proj\ENG236\Ch5
• Set the project name, e.g. LibCat
• However, when choosing the Application type in the Application Settings window, choose Static library and uncheck the option Precompiled header
5. Basic Object Oriented Programming
Computer Programming5. Basic Object Oriented Programming
48
48
Computer Programming
• In Visual C++ 2017 Solution Explorer, under Header Files , right-click Add → New Item ... and choose Header File (.h )
• Set the Header File name to, e.g. CatClass
• Click Add and the header file CatClass.h will be added to the project LibCat
• Type the class declaration
5. Basic Object Oriented Programming
49
Computer Programming
• Type your class declaration here• Remember to comment your codes• Type your class declaration here• Remember to comment your codes
5. Basic Object Oriented Programming
50
Computer Programming
• In Visual C++, click Project/Add New Item... and choose C++ File (.cpp )
• Set the C++ source file name, e.g. CatCodes
• Click OKand the C++ source file CatCodes.cpp will be added to the project LibCat
• You may verify it by checking the Solution Explorer
• Type the codesfor the implementation of the member functions
• Remember to include your header fileand be careful of its location
• Build the library by clicking Build Solution .Give LibCat.lib
5. Basic Object Oriented Programming
51
5. Basic Object Oriented Programming
Computer Programming
• You need to enter the correct path of the header file• It shows that the CatClass.h is in the current
folder of CatCodes.cpp
• You need to enter the correct path of the header file• It shows that the CatClass.h is in the current
folder of CatCodes.cpp
• After building the library, the result is shown • After building the library, the result is shown
Solution Explorerwindow
52
Computer Programming
Step 5: Send the library and header file to the System Analyst
• Locate the files CatClass.h and LibCat.lib and send to the System Analyst
• CatClass.h shows the class definition
• From its contents, the System Analyst knows how to use the class
• LibCat.lib contains the codes for the implementation of the member functions
• It is in object code formsuch that even the System Analyst cannot interpret or modify the codes.
5. Basic Object Oriented Programming
53
Computer Programming5. Basic Object Oriented Programming
e:\Vs_Proj\ENG236\Ch5\LibCat\LibCate:\Vs_Proj\ENG236\Ch5\LibCat\LibCat
e:\Vs_Proj\ENG236\Ch5\LibCat\debuge:\Vs_Proj\ENG236\Ch5\LibCat\debug
54
Step 6: Integrating into the application
Computer Programming
• 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
#ifndef Preprocessor_Identifier#define Preprocessor_Identifier
.
.
.
#endif
Avoiding Multiple Inclusion of Header Files
Computer Programming5. Basic Object Oriented Programming
59
Using Preprocessor Directive #ifndef
// timetype .h FOR COMPILATION THE CLASS DECLARATION IN
// SPECIFICATION FILE FILE timetype.h WILL BE INCLUDED ONLY ONCE
#ifndef TIME_H #define TIME_H // timetype .cpp // client.cpp
// IMPLEMENTATION FILE // Appointment programclass TimeType{ #include “timetype.h” #include “timetype.h”
public:. . . . . . int main ( void )
{private: . . .
. . . }} ;#endif
Computer Programming5. Basic Object Oriented Programming
60
Computer Programming
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
Computer Programming6. Pointers and Arrays
65
Free Storeor
the heap
Global Name SpaceCode SpaceThe Stack
How memory is used in C++?
Computer Programming6. Pointers and Arrays
funcB(){ Cat Frisky;
return;}
funcA(){ int a;
return;}
main(){ Statements;
funcA();Statements;funcB();Statements;
}
66
• A variable is a storage spacein memory
• Every variable has amemory address
What is the Address of a Variable?
0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address
Memory
Variables char a int b short int c bool d
30 0A 21 3A 51 44 20 00
a = 30 Address of a = 0100
b = 0A 21 3A 51 Address of b = 0101
c = 44 20 Address of c = 0105
Computer Programming6. Pointers and Arrays
All values written in
hexadecimal but
binary in reality
The character '0'
Each byte has an address
Each variable has the
starting-byte address
67
• In C++, the symbol & is used to indicate the address of a variable #include <iostream>
using namespace std;int main(){ unsigned short shortVar = 5;
unsigned long longVar = 65535;long sVar = -65535;cout << "shortVar:\t" << shortVar;cout << "\tAddress of shortVar:\t";cout << &shortVar << "\n";cout << "longVar:\t" << longVar;cout << "\tAddress of longVar:\t";cout << &longVar << "\n";cout << "sVar:\t\t" << sVar;cout << "\tAddress of sVar:\t";cout << &sVar << "\n";return 0;
}
The addresses of shortVar ,
longVar and sVar
What is the Address of a Variable?
Computer Programming6. Pointers and Arrays
68
• Variable and address of a variable are different
What is the Address of a Variable?
Computer Programming6. Pointers and Arrays
69
Computer Programming6. Pointers and Arrays
What is a Pointer?• In many situations, we want to store the address of a
variable into a particular memory location
0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address
Memory
Variables char a int b (address of a) pa
10 0A 21 3A 51 00 0100 00
• 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 .
pa is the pointer of a
70
Computer Programming6. 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 good enough, since it does not tell the nature of aNot good enough, since it does not tell the nature of a
� How about (address of a character) pa;
Better, but look too clumsy Better, but look too clumsy
71
Computer Programming6. 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 *
� means the contentof an address
0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address
Memory
Variables char a int b char *pa
10 0A 21 3A 51 00 0100 00
• char *pa indicates that the memory contentof the address stored inpa is a character. pa is indirectlydeclared to be an address of character.
pa 's content is an address, the memory
content of that address is a character
72
What is a Pointer?
char *pa, a= 0x30 ; // 48
cout << a; // a = '0'
pa = &a; // pa = 0100
cout << *pa; // *pa = '0'
*pa = 49; // a = '1'
cout << a;
Computer Programming6. Pointers and Arrays
0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address
Memory
Variables char a int b char *pa
30 0A 21 3A 51 00 0100 00
• We can modify the content of a memory location using pointer
We modify a indirectly by using its address
73
Pointers� Special variables that only hold memory addresses� Hold the location (address) of information, not the
information itself� Pointers are declared using a “*” after the type
int a = 10 ;
int * p; // A POINTER VARIABLE!!!!
p = &a;
You have to specify the pointer type!
Computer Programming6. Pointers and Arrays
74
Don’t get confused
� pointer p does not hold the value of a� it points to the memory location of a� pointer p is a variable
– and it has its own memory location
1 0 0 0 2
1048575
1048574
1048573
Pointer Constants
0
a p
1048572
1048571
1048570
Computer Programming6. Pointers and Arrays
75
Examplesint x=7; int *p, *q; p = &x; q = &x;
Computer Programming6. Pointers and Arrays
76
Pointer Indirection (Pointer to Pointer)
What is the result?
58 58 58
Computer Programming6. Pointers and Arrays
77
Computer Programming6. 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// Don’t let it become wild pointer (point to unknown)myAge = 5;cout << "myAge: " << myAge << "\n";pAge = &myAge; // assign address of myAge to pAgecout << "*pAge: " << *pAge << "\n\n";cout << "*pAge = 7\n";*pAge = 7; // *pAge=7, not pAge=7 , sets myAge to 7cout << "*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 Programming6. Pointers and Arrays
79
80
Why Pointer? - Using Free Store• Pointer allows us to handle the memory in Free Store
• The memory Free Store is opened to all functions
• Pointer helps us to identify the part of memory in Free Store that is being used by a particular function or object
• To use the memory in Free Store:
1. Claim to the systemhow much memory is required
2. System allocates a memory space with size big enough
3. System returns a pointer valuewhich is the startingaddress of that memory space
4. When the memory space is not required, release it back to the systemfor other functions.
Computer Programming6. Pointers and Arrays
81
new operator� General form:
new type [num_elements]– type is data type of array elements– num_elements is number of array elements
� Reserves memory but does NOT fill with values– new returns address of memory it reserves– Value assigned to pointer variable of same type
int* array_address;array_address = new int [10];
array_address[0], … array_address[9]*array_address, … *(array_address+9)
Computer Programming6. Pointers and Arrays
82
new and delete
unsigned short int * pPointer;pPointer = new unsigned short int;:// after using the memory space:delete pPointer; // return it to system
Claim a piece of memory in Free Store with size that is equal to an unsigned short
integer
The keywords new and delete help us claim and release memory in Free Store
int * pPointer2;pPointer2 = new int[2];:// after using the memory space:delete [] pPointer2; // return it to system
We claim memory with size equals to 2 integers.
pPointer2 now points to the starting address of this
memory space
Computer Programming6. Pointers and Arrays
Results unpredictable if no []
83
delete operator
� General form:delete [ ] array_address;
– array_address is pointer variable
� Releases memory stored at address indicated� Knows size of memory reserved by new and
releases memory for all the array� delete address;
– deletes memory for single element
Computer Programming6. Pointers and Arrays
84
8003 8004 8005 8006 8007 8008 8009 800A 800B 800CAddress
Memory
Free Store
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;
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;
}
Computer Programming6. Pointers and Arrays
92
Creating Objects in the Free Store• Similar to integer, we
can create objectsin the Free Store
Cat *pCat = new Cat;
Free Storeor
the heap
Global Name SpaceCode SpaceThe Stack
Size enough for a Cat
pCat
• pCat stores the beginning addressof the memory allocated
• When the object is created, its constructor is called
Computer Programming6. Pointers and Arrays
Object identified by a pointer.
93
Deleting Objects• Objects in the Free Store can also be deleted
Cat *pCat = new Cat;
delete pCat;
• pCat becomes an identifier of the object created
• When an object is deleted, its destructor will be called
• Hence the destructor of Cat will be called when the keyword delete is used in the above
• (The destructor will also be called if the function that creates the object finishes.)
Computer Programming6. Pointers and Arrays
94
#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";}
The class SimpleCat
Constructor
Destructor
Example
Computer Programming6. Pointers References and Arrays
95
int main(){
cout << "SimpleCat Frisky...\n";SimpleCat Frisky;cout << "SimpleCat *pRags = new SimpleCat...\n";SimpleCat * pRags = new SimpleCat;cout << "delete pRags...\n";delete pRags;cout << "Exiting, watch Frisky go...\n";return 0;
}
Output of the program
Computer Programming6. Pointers and Arrays
pRags in the stack, *pRags in the heap
96
Accessing Members of Objects• To access members of an object, the operator (. ) is used
SimpleCat *pCat = new SimpleCat;
(*pCat).SetAge(2);
The object pointed by pCat
The member function of the
object
Input parameter of the member
function
• In C++, a shorthand is provided for such member access
SimpleCat *pCat = new SimpleCat;
pCat -> SetAge(2); // The same as before
The Same
Computer Programming6. Pointers and Arrays
97
Pointers to Objects
� Special arrow operator ->– Negative and greater than symbol with no space between– Used to access members with object's address
� Declaring pointer Class_name* ptr_name;� Initializing pointer ptr_name = &object_name;� Calling member function (2 argument example)
ptr_name -> member_fun(arg1, arg2);
(*ptr_name).member_fun(arg1, arg2);ptr_name[0].member_fun(arg1,arg2);
Computer Programming6. Pointers and Arrays
98
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 1Object::~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?
Computer Programming
99
Answer4 bytes on the stack to hold Obj which contains a pointer count
4 bytes on the heap that is pointed by count of Obj
Free Storeor
the heap
Global Name SpaceCode SpaceThe Stack4 bytes: count
4 bytes: *count
Obj
Computer Programming6. Pointers and Arrays
100
Using the this PointerCan be used to access members that may be hidden by parameters with the same name: class SomeClass
{private:
int num;public:
void setNum(int num){ this->num = num; }
};
Computer Programming6. Pointers and Arrays
101
0000000100020003000400050006000700080009
Pointers Arithmetic• Pointers can be added or subtractedfrom one another
if they are of the same type
Address
Memory
Variables short int *a, *b
10 0A 21 3A 51 44 20
cout << "a = " << a << endl; // Assume a = 0000
b = a + 1;
cout << "b = " << b << endl; // b = 0002
cout << "b - a = " << b-a << endl; // b - a = 1
Computer Programming6. Pointers and Arrays
102
Pointer Variables and Arithmetic
� Declare variable as pointerdouble* b;
– Holds address
� Can perform addition and subtraction– Purpose of add is to advance to subsequent cell
b + 1 (double is 8 bytes, so adds 8 bytes)– Subtraction goes back to previous memory cell
b – 1 (goes back 8 bytes)
Computer Programming6. Pointers and Arrays
103
Pointers Arithmetic• The same applies to objects
0000 0001 0002 0003 0004 0005 0006 0007 0008 0009Address
Memory
Variables Cat *a = new Cat; //Assume Cat takes 6 bytes
Cat *a = new Cat;
Cat *b;
cout << "a = " << a << endl; // Assume a = 0000
b = a + 1; // Don't touch *b as the memory is not from new
cout << "b = " << b << endl; // b = 0006
cout << "b - a = " << b-a << endl; // b - a = 1
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.
#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;
}
Computer Programming6. Pointers and Arrays
105
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
sequenceis named as shortArray
shortArray[ 0] 000B 000C ... ... 0037 0038 0039 003A
Memory
Variables short shortArray[25]; //declaration
10 0A 21 3A ... ... 20 2A 4B 40
Computer Programming6. Pointers and Arrays
shortArray[1] shortArray[ 24]
In consecutive memory
107
Array Element• In an array, an array elementis 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
:
shortArray[24] is the last element
• No shortArray[25] !!!
• Do not try to use shortArray[25], result unpredictable.
25 short 25 short
integers
Computer Programming6. Pointers and Arrays
108
Computer Programming6. Pointers and Arrays
short shortArray[25];
0009 000A 000B 000C ... ... 0037 0038 0039 003AAddress(Hex)
Memory
Variables short shortArray[25];
10 0A 21 3A ... ... 20 2A 4B 40
• So shortArray[0] = 0x100A; // 4106 in deciaml
shortArray[1] = 0x213A; // 8506 in decimal
:
shortArray[23] = 0x202A;
shortArray[24] = 0x4B40;
Declaration
Assignment statements
109
Assigning Values to Individual Array Elements
float temps[ 5 ] ; // allocates memory for array
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
Computer Programming6. Pointers and Arrays
116
int Minimum(const int A[], int size)
{int SmallestValueSoFar = A[0];
for (int i = 1; i < size; ++i)
if (A[i] < SmallestValueSoFar )
SmallestValueSoFar = A[i];
return SmallestValueSoFar ;
}
Passing An Array Notice brackets are empty
First element
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;
Computer Programming6. Pointers and Arrays
117
#include <iostream>using namespace std;
void Obtain ( int [ ], int ) ; // prototypes herevoid Print ( const int [ ], int ) ;
using namespace std ;
int main( ) {
int temp[31] ; // array to hold up to 31 temperaturesint numDays;
cout << “How many daily temperatures? ” ;cin >> numDays ;
Obtain( temp, numDays ) ; // call passes value of numDays and // address of array temp to function
cout << numDays << “ temperatures“ << endl ;Print ( temp, numDays ) ;return 0 ;
}
Example with Array Parameters
Computer Programming6. Pointers and Arrays
118
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
required
int val[ ][4] = { 8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10 }
Computer Programming6. Pointers and Arrays
121
Initialize Multidimensional Arrays• Multidimensional Arrays can also be initialized during
declaration
int SomeArray[5][2] = { {0,0},{1,2},{4,6},{7,2},{4,4}};
int AnotherArray[5][2] = {0,0,1,2,4,6,7,2,4,4};
0 0
1 2
4 6
7 2
4 4
0 1
4
3
2
1
0
Computer Programming6. Pointers and Arrays
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
const int NUM_STATES = 50 ;const int NUM_MONTHS = 12 ;int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ;
� In memory, C++ stores arrays in row order. The first row is followed by the second row, etc.
Base Address
. . .
12 highs for state 0 12 highs for state 1 etc.
first row second row
8000 8048 8096
STORAGE rows columns
Computer Programming6. Pointers and Arrays
123
Viewed another way . . .stateHighs[ 0 ] [ 0 ]stateHighs[ 0 ] [ 1 ]stateHighs[ 0 ] [ 2 ]stateHighs[ 0 ] [ 3 ]stateHighs[ 0 ] [ 4 ]stateHighs[ 0 ] [ 5 ]stateHighs[ 0 ] [ 6 ]stateHighs[ 0 ] [ 7 ]stateHighs[ 0 ] [ 8 ]stateHighs[ 0 ] [ 9 ]stateHighs[ 0 ] [10 ]stateHighs[ 0 ] [11 ]stateHighs[ 1 ] [ 0 ]stateHighs[ 1 ] [ 1 ]stateHighs[ 1 ] [ 2 ]stateHighs[ 1 ] [ 3 ]
.
.
.
To locate an element such asstateHighs [ 2 ] [ 7] the compiler needs to know that there are 12 columnsin this two-dimensional array.
At what address will stateHighs [ 2 ] [ 7 ] be found?
Assume 4 bytes for type int.
Base Address 8000
Computer Programming6. Pointers and Arrays
124
void FindAverages( /* in */ const int stateHighs [ ] [ NUM_MONTHS] , /* out */ int stateAverages [ ] )
{
int state;int month;int total;for ( 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 ) ;
}}
Computer Programming6. Pointers and Arrays
125
Matrix Addition Solution
void MatrixAdd(const float A[][MaxCols],
const float B[][MaxCols], float C[][MaxCols],
int m, int n)
{
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
C[i][j] = A[i][j] + B[i][j];
}
Notice only first brackets are empty
Computer Programming6. Pointers and Arrays
126
const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furnitureconst NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson
int monthlySales [ NUM_DEPTS ] [ NUM_MONTHS ] [ NUM_STORES ] ;monthlySales[ 3][ 7][ 0]
sales for electronics in August at White Marsh
12 MONTHS columns
5 D
EP
TS
row
s
Computer Programming6. Pointers and Arrays
127
Array and Pointer• C++ allows the flexibility for user to useArray and
Pointer interchangeably
• The name of an array is a constant pointerpointing to the first element of the array
int a,b;
int SomeArray[5] = {10,20,30,40,50};
a = *SomeArray; // a = 10
b = *(SomeArray+1); // b = 20, pointer arithmetic
• Compiler does all the calculation
• SomeArray+1 does not add 1 to SomeArray but add 4(1 integer needs 4 bytes for storage) and point to the next element in the array
Computer Programming6. Pointers and Arrays
128
0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address
The Stack
SomeArray[5]
10 20 30 40
Computer Programming6. Pointers and Arrays
50
x = *SomeArray;
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
0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address
The stack
pSomePointer = 0104
10 11 12 13 14
SomeArray[]SomeArray[1] andpSomePointer[1] are exactly the same.
0104
pSomePointer
130
De-referencing An Array Name� Using pointers can be faster than using array subscripts
Use a for loop to step through the array:for(int i=0; i<SIZE; i++) {
cout << *(a + i) << endl;
}
Computer Programming6. Pointers and Arrays
131
Relationship Between Pointers and ArraysArrays and pointers are closely related
Array name like a constant pointerPointers can do array subscripting operationsExample: Declare an array b[ 5 ] and a pointer bPtr
int b[5], *bPtr;bPtr = b;// To set them equal to one another// The array name (b) is actually the address of first element of the array
bPtr = &b[ 0 ];// Explicitly assigns bPtr to address of first element of b
To access element b[ 3 ]:x=*( bPtr + 3 ) // Where n is the offset. Called pointer/offset notation
x=bptr[ 3 ] // Called pointer/subscript notation// bPtr[ 3 ] same as b[ 3 ]
x=*( b + 3 ) // Performing pointer arithmetic on the array itself
Computer Programming6. Pointers and Arrays
132
– Pointers and arrays can be used interchangeably.– The array name is equivalent to the address of the first
element in the arrayExample:
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+1a[i] ⇔ *(pa+i) ⇔ pa[i] ⇔ *(a+i)&a[i] ⇔ pa+i ⇔ a+ia[i]+=5 ⇔ *(pa+i)+=5 ⇔ pa[i]+=5
Example:f(int s[] ){ … }
f(int *s ){ … }
⇔
Relationship Between Pointers and Arrays
Computer Programming6. Pointers and Arrays
133
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 elementsof 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.
Computer Programming6. Pointers and Arrays
The array itself is still in the stack.
134
6. Pointers and Arrays
#include <iostream>using namespace std;class CAT{public:
CAT() {itsAge = 1;}~CAT() {}int GetAge() const {return itsAge;}void SetAge(int age) {itsAge = age;}
private:int itsAge;
};int main(){ CAT *Family[500];
int i;for (i=0; i<500; i++){ Family[i] = new CAT; }Family[255]->SetAge(1);for (i=0; i<500; i++){ delete Family[i] ; }return 0;
}
Creating 500 CATobjects may use up all memory in the stack
Hence only an array of 500 pointers of CATobjects are created in the stack
Each CATobject is located in the Free Store by the keyword new
To access member of a particular CATobject, use the corresponding
pointer in the array
Computer Programming
135
Free Storeor
the heap
Global Name SpaceCode SpaceThe Stack
CAT 0 CAT 1
CAT 2
CAT 499
...
Array of Pointers
An array of pointers called Family is kept to point to
different elements in Free Store
Computer Programming6. Pointers and Arrays
(*Family[0])
136
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 enoughto point to the Array itself but not an individual element
• This becomes a pointer of array.
CAT *Family = new CAT[500];
int a = 0, b=0;
(Family+255)->SetAge(10);
a = (Family+255)->GetAge(); // a = 10
b = Family[255].GetAge(); // b = 10
delete [] Family;
Family is the pointer of array and points to
Family[0] in Free Store
Family is the pointer of array and points to
Family[0] in Free Store
Individual element of the array of the CATobjects
can be accessed by pointer arithmetic
Individual element of the array of the CATobjects
can be accessed by pointer arithmetic
Computer Programming6. Pointers and Arrays
137
Pointer of Array
Free Storeor
the heap
Global Name SpaceCode SpaceThe Stack
CAT 0 CAT 1 ... CAT 499
A pointer Family is kept to point to the beginning memory location of an array
of CATobjectsin Free Store
Computer Programming6. Pointers and Arrays
Family[0] Family[499]
138
6. Pointers and Arrays
#include <iostream>using namespace std;class CAT{public:
CAT() {itsAge = 1;}~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;return 0;
}
Arrays created in Free Store can also be deleted
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
char Greeting[] =
{'H','e','l','l','o',' ','W','o','r','l','d', '\0' };
• A string can be simply initialized as follows:
The null characterrepresents the end of string; it must be added.
• However, this method can easily introduce error
• C++ provides a shorthand that makes use of the double quote " ".
char Greeting[] = {"Hello World"};Totally 12bytes are allocated
for Greeting .Null character is
automatically generated.
Computer Programming6. Pointers and Arrays
Size of
array is 12
The braces can be removed
142
C strings � char arrays
� char array will contain an extra null character at the end of the string
Example:char codes[] = “sample”;
115 97 109 112 108 101 0
Computer Programming6. Pointers and Arrays
608_01
144
• Characters and ASCII codes:char x;
x = ‘a’; /* x = 97*/
Notes:– ‘a’ and “a” are different; why?
‘a’ is the 97“a” is an array of characters, { ‘a’, ‘\0’} or {97, 0}
–“a” + “b” +”c” is invalid but ‘a’+’b’+’c’ = ? (hint: ‘a’ = 97 in ASCII)
Character and C String
1 38
‘a’ + ‘b’ + ‘c’ = 97 + 98 + 99 = 294 = 256 + 38 -> 38
in the memory
Computer Programming6. Pointers and Arrays
145
Computer Programming6. 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. 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>
#include <cstring>
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 null ) to be copied
State the definition of strncpy()
Computer Programming6. Pointers and Arrays Warning: unsafe
150
Exercise 6.2ca. Write a program that
creates an array of 3 objects of the class ACCOUNTin the free store.
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;}
Computer Programming6. Pointers and Arrays
Pointer of array
151
String Conversion Functions� Conversion functions
– In <cstdlib> (general utilities library)
� Convert strings of digits to integer and floating-point values
Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double .
int atoi( const char *nPtr ) Converts the string nPtr to int .
long atol( const char *nPtr ) Converts the string nPtr to long int .
double strtod( const char *nPtr, char **endPtr )
Converts the string nPtr to double .
long strtol( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to long .
unsigned long strtoul( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to unsigned long .
Computer Programming6. Pointers and Arrays
152
atoi and atol
� atoi converts alphanumeric to i nt � atol converts alphanumeric to l ong
int atoi(char *numericStr)
long atol(char *numericStr)
� Examples:int number; long lnumber;number = atoi("57");
lnumber = atol("50000");
Computer Programming6. Pointers and Arrays
153
atof
� atof converts a numeric string to a floating point number, actually a doubledouble atof(char *numericStr)
� Example:double dnumber;
dnumber = atof("3.14159");
Computer Programming6. Pointers and Arrays
String Conversion Functions
154
Computer Programming6. Pointers and Arrays
A few more library functions• To measure the
length of a string, the function strlen() is useful
• To combine two strings into one, we can use the function strcat() .
#include <iostream>
#include <cstring>
using namespace std;
int main()
{ char String1[100];
cout << "Please enter a word: ";
cin >> String1 ;
char String2[] = " has ";
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;
}
Convert an integer into a string
Convert an integer into a string
Decimal radix
Append
a string
5 warnings
Return an int
155
itoa
� itoa converts an int to an alphanumeric string� Allows user to specify the base of conversion
itoa(int num, char *numStr, int base)
� Example: To convert the number 1200 to a hexadecimal string
char numStr[10];
itoa(1200, numStr, 16);
� The function performs no bounds-checking on the array numStr
Computer Programming6. Pointers and Arrays
A few more library functions
156
strcat
strcat(char *dest, char *source)
� Takes two C-strings as input. It adds the contents of the second string to the end of the first string:
char str1[15] = "Good ";
char str2[30] = "Morning!";
strcat(str1, str2);
cout << str1; // prints: Good Morning!
� No automatic bounds checking: programmer must ensure that str1 has enough room for result
Computer Programming6. Pointers and Arrays
A few more library functions
157
Computer Programming6. Pointers and Arrays
• We can compare if two strings are the same using the function strcmp().
#include <iostream>
#include <cstring>
using namespace std;
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;
}
Syntax:int strcmp(string1, string2)Return 0 if string1 is the same as string2 ; otherwise returns a +ve or −ve number.
Syntax:int strcmp(string1, string2)Return 0 if string1 is the same as string2 ; otherwise returns a +ve or −ve number.
Get one line of text (including the spaces in between)
No warning
158
strcmpint strcmp(char *str1, char*str2)
� Compares strings stored at two addresses to determine their relative alphabetic order:
� Returns a value:less than 0 if str1 precedes str2
equal to 0 if str1 equals str2
greater than 0 if str1 succeeds str2
if(strcmp(str1, str2) == 0)cout << "equal";
else cout << "not equal";
Computer Programming6. Pointers and Arrays
A few more library functions
159
Character PointersString constant acts like a character pointerchar *pc = “ABCDE”; // declare a character pointer variable
Variable Address Valueconstant 731 ‘A’constant 732 ‘B’constant 733 ‘C’constant 734 ‘D’constant 735 ‘E’constant 736 ‘\0’pc 800 731
char s1[] = “abc”;
Variable Address Values1[0] 900 ‘a’s1[1] 901 ‘b’s1[2] 902 ‘c’s1[3] 903 ‘\0’
‘A’
‘B’
‘C’
‘D’
‘E’
‘\0’
731
732
733
734
735
736
731800
Computer Programming6. Pointers and Arrays
160
� Arrays can contain pointers� For example: an array of strings
char *suit[4] = {"Hearts", "Diamonds",
"Clubs", "Spades"};– Strings are pointers to the first character– char * – each element of suit is a pointer to a char
– The strings are not actually stored in the array suit , only pointers to the strings are stored
– suit array has a fixed size, but strings can be of any size
Arrays of Pointers
suit[3]
suit[2]
suit[1]
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’
’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’
’C’ ’l’ ’u’ ’b’ ’s’ ’\0’
’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’
Computer Programming6. Pointers and Arrays
161
Syntax:int *pi[3]; /* pi[0], pi[1], pi[2] */
float *pf[3]; /* pf[0], pf[1], pf[2] */
Example 1:
int i=1, j=2, k=3;
int *pi[3] = {&i, &j, &k};Variable Address Value
constant 90 ‘A’constant 91 ‘B’constant 92 ‘C’constant 93 ‘\0’constant 94 ‘D’constant 95 ‘E’constant 96 ‘F’constant 97 ‘\0’constant 98 ‘G’constant 99 ‘H’Constant 100 ‘\0’pc[0] 200 90pc[1] 202 94pc[2] 204 98
Pointer Arrays
Constcan not bechanged
Variable Address Value
i 80 1
j 82 2
k 84 3
pi[0] 100 80
pi[1] 101 82
pi[2] 102 84
Example 2:
char *pc[3]={“ABC”, “DEF”, “GH”};
Computer Programming6. Pointers and Arrays
162
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:
string phrase, word1(“Hello “), word2(“World”);phrase = word1 + word2;cout << phrase << endl;
� The output will be Hello World
6. Pointers and Arrays
Computer Programming
164
� Characteristic use of the getline function follow:
#include <iostream>
#include <string>using namespace std;//. . .string str1;getline(cin, str1);//insert into str12 all input up to ‘\n’//getline discards the ‘\n’
� NOTE THAT class string objects do not range check index values .� If you want range checked indexing into strings, us e the string member
function at(int_index) .str1.at(9); //Checks index value 9 for legality in str1.
//If legal,returns the character at index value 9.
The C++ Standard string class 6. Pointers and Arrays
Computer Programming
165
650
166
� argc and argv // int main( int argc, char* argv[ ])
– In environments those support C++, there is a way to pass command-line arguments or parameters to a program when it begin executing.
– When main is called to begin execution, it is called with two arguments –argc and argv
� argc : The first (conventionally called argc) is the number of command-line arguments the program was invoked with
� argv : The second (conventionally called argv) is a pointer to an array of character strings that contain the arguments, one per string.
Example:
if echo is a program and executed on command prompt, such asC:\> echo hello world
Command-Line Arguments
pointer arrayargv
argc
e c h o \0
h e l l o \0
w o r l d \0null3
Computer Programming6. Pointers and Arrays
167
Command-Line Processing
• In many operating systems, command-line optionsare allowed to input parametersto the program
SomeProgram Param1 Param2 Param3
• To achieve this, main() allows two input parameters to hold the command-line options.
int main(int argc, char *argv[]){ return 0;}
argc stores the number of parameters
argv is an array. Each element of the array is a
character pointer
Computer Programming6. Pointers and Arrays
e.g.ipconfig /all
You can also write *argv[]as**argv
The values of argc and argv[] are provided indirectly
168
Computer Programming6. Pointers and Arrays
ExampleSomeProgram Param1 Param2 Param3
int main(int argc, char *argv[]){
// function statements herereturn 0;
}
argc = 4argc = 4
argv[0] = "SomeProgram"argv[1] = "Param1"argv[2] = "Param2"argv[3] = "Param3"
argv[0] = "SomeProgram"argv[1] = "Param1"argv[2] = "Param2"argv[3] = "Param3"
main() is inside the projectSomeProgram
i.e. argv[0][0] is 'S'
169
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;
}
Computer Programming6. Pointers and Arrays
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.
x and y are swapped only in swap() but not
in main()
Computer Programming6. Pointers and Arrays
173
1. At main()1. At main()
Computer Programming6. Pointers and Arrays
0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address
The stack
Variables
5 10
x y
x and y of main()
4. When swap() returns4. When swap() returns
5 10
x y
x and y of swap()
2. When swap() is called2. When swap() is called
pass-by-value
3. When x and y is swapped3. When x and y is swapped
10 5
x y
x and y of swap()
temp = x;x = y;y = temp;
174
Pass by Pointers
• pointerallows passparameters by reference.
#include <iostream>using namespace std;void swap(int *px , int *py ){ int temp;
temp = *px;*px=*py;*py=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;
}
The addressesof x and y in main() are passed
to swap()
Computer Programming6. Pointers and Arrays
175
Parameter Passing - by Pointers� Pointer px refers to the memory cell of a.
Computer Programming6. Pointers and Arrays
176
Computer Programming6. Pointers and Arrays
0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address
The stack
Variables
5 10
x y
1. At main()1. At main()
x and y of main()
0100 0104
px py
px and py of swap()
2. When swap() is called2. When swap() is called
pass-by-ref
10 5
temp = *px; //5*px = *py; //10*py = temp; //5
3. When *px and *py is swapped3. When *px and *py is swapped
0100 0104
px py
px and py of swap()
10 5
4. When swap() returns4. When swap() returns
177
Return Multiple Values• Normal function
can only return 1 value
• If more than 1 values are to be returned, it can be done by passing two or more parametersto a function by reference.
#include <iostream>using namespace std;void opt(int, int * , int * ); //prototypeint 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;
}
Computer Programming6. Pointers and Arrays
sqr and cub of main()are changed by opt()
178
??
0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address
The stack
Variables
3 ??
num sqr
num, sqr and cub of main()
1. At main()1. At main()
Computer Programming6. Pointers and Arrays
cub
pass-by-ref
0104 0108
pS pC
n, pS and pC of opt()
2. When opt() is called2. When opt() is called
3
n
pass-by-value
*pS = n*n;*pC = n*n*n; 3. When *pS and *pC are
computed in opt()3. When *pS and *pC are computed in opt()
0104 0108
pS pC
n, pS and pC of opt()
3
n
9 279 27
4. When opt() returns4. When opt() returns
179
Computer Programming6. Pointers and Arrays
Passing an array of parameters to a function
• To save effort from separately passing a number of parameters to a function, they may be passed as an array.
#include <iostream>#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;
}
void opt( char * str ){ strcpy(str,"New String");}
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.
Computer Programming6. Pointers and Arrays
Only swap the name, not the object
182
#include <iostream>#include <cstring>using namespace std;class CAT{public:
CAT(char * firstname) {strncpy(name,firstname,79);}~CAT() {;}char * GetName() {return name;}void SetName(char *nameinput) {strncpy(name,nameinput,79);}
private:char name[80];
};
void nameswap(CAT *CatA, CAT *CatB);
Exercise 6.3 (Cont)
Computer Programming6. Pointers and Arrays