Вы находитесь на странице: 1из 227

Object-Oriented Programming Using C++

2nd Year
Department of Software Engineering
College of Engineering
University of Salahaddin-Erbil

About This Course, 1


In the first year we studied Procedural Programming in C++; this
course builds on that course and will introduce Object-Oriented
programming in C++.
When programs reach 30,000 to 50,000 lines of code, they become
very complex and difficult to comprehend. This is when you have to
look for another way to tackle large and complex programs.
Object-Oriented (OO) programming reduces this problem of
complexity. C++, a successor to C, was invented to support OO
programming and to be a better C.
So, this course will be on OO programming using C++. Last years
course is a pre-requisite for this course. Anyone who has forgot
using C++ is strongly advised to quickly refresh their C++ knowledge.
Object-Oriented Programming

About This Course, 2


In the first 2 to 3 lectures, we will briefly go over some of the
important topics we studied last year, like arrays, structures,
functions, file I/O and pointers. Also we will quickly introduce a
number of minor topics which we should have studied last year.
Then on, we will start on OO programming concepts until the end of
the year. You should remember that this is an important subject; it
is also a hard subject! There is a lot of detail that you will
need to master. You are strongly advised to attend all lectures and
lab sessions, because there is a lot of material to be covered and
lectures will NOT be repeated.
As well as your scheduled 2 hour weekly lab sessions, you should try
to spend at least 2 hours per week in the lab to complete exercises
and write programs. Remember that only practice makes a C++ guru.
Object-Oriented Programming

About This Course, 3


There will be two lectures, 1 hour each, per week and a two-hour
supervised lab session every week. You should attend all lectures
and lab sessions. You should also spend at least 2 hours per week in
the open lab to complete exercises and assignments.
There will be 2 marked assignments for you to perform; each will
carry a weight of 10% toward the final grade for this course.
There will not be a theory exam for this course(except the final)
There will be a practical exam with a weight of 20% toward the end
of the year.
The final exam will carry 60% of the total grade for this course.
Object-Oriented Programming

About This Course, 4


I will try to cover most of the syllabus in these lecture notes. But
for further detail and reference you might find the following text
books useful for this course.
1. Problem Solving, Abstraction and Algorithms using C++
By: Friedmann and Koufmann, 1995
2. Problem Solving with C++
By: Walter Savitch, 3rd, 2001
3. C++ The Complete reference
By: Herbert Schildt, 1998
Copies of these text books are available in the college library for
you to borrow.

Object-Oriented Programming

The Syllabus
We will attempt to cover the following topics during this course:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

Review of arrays, pointers, structures and file I/O


Introduction to Object-Oriented Programming
The Standard String Class
Classes
The Big Three
Function Overloading
Operator Overloading
Inheritance
Virtual Functions
Templates
Exception Handling
Standard Template Library (STL)

Object-Oriented Programming

Review of Last Year (arrays)


A C++ array is an indexed collection of variables which are all
1. of the same data type
2. referred to by a common name
3. stored in contiguous memory locations
Example,
int marks[]={56, 76,45,77,34};
The array name or identifier is called marks; this array has five
elements of type integer, that is its size is 5;
Array elements are zero-indexed: the first array elements index is
0 and the last elements index is one less than array-size (4); the
most common error associated with arrays is the out-of-boundserror: you cannot expect marks[5] to have a defined value. Your
index is out of bounds.
Object-Oriented Programming

Review of Last Year (Pointers 1)


A C++ pointer is a variable that holds a memory address. This
address could be the memory address of another variable in the
memory. Here we declare a pointer of type integer:
int *p, i=0;
This declaration says that the pointer p can point to variables of
type integer. The statement
p=&i;
assigns to p the memory address of i. And the statement
cout<<*P;
outputs 0 onto the screen. *p means location pointed to by p.
You can compare two pointers in a relational expressions as in
if (p==q)
cout<<p and q point to the same location;
else
cout<<p and q point to different locations;
Object-Oriented Programming

Review of Last Year (Pointers 2)


There is a special relationship between arrays and pointers in C++,
consider the following code:
char str[20]=HELLO, *p;
p=str; //set p to address of first element of str
cout<<str[0]; //print H
cout<<p[0]; //print H
cout<<*p;
//print H
cout<<*(p+0); //print H
cout<<str[4]; //print H
cout<<*(p+4); //print O

Another example: (the second function is a lot shorter and faster)


void print(char *s)
{
int i;
for(i=0; s[i]; i++)
cout.put(s[i]);
} //until s[i] is NULL (\0)
Object-Oriented Programming

void print(char *s)


{
while (*s)
cout.put(*s++)
}
//*(s++)

Review of Last Year (Pointers 3)


You can have a pointer to an array of pointers as the following
shows:
int *array[5], x=1;
array[1]=&x;
cout<<x<< is the same as <<*array[1]<<endl;

Here, array is not a pointer to integers; it is a pointer to an array


of pointers to integers. Each element of the array is a pointer to an
integer.
If you want a pointer not to point to anywhere in the memory you
can set its value to NULL as in
char *p=Hello;
p=NULL;
//p no longer points to anything
if (p!=NULL) cout<<p;
Object-Oriented Programming

10

Review of Last Year (Structures)


A structure is a collection of related variables. When you define a
structure you define a new composite data type. Consider this code:
struct address
{
int house_no;
char *street_name; //or char street_name[20]
char *town;
} my_address, your_address;

Here my_address and your_address are of type address.


To initialise a structure variable:

address his_address={ 38, Oxford St, London};

You can also assign two structure variables as in


your_address=his_address;

The contents of the two structure variables will be the same.


Also you can pass an entire structure variable to a function. It will
be a call by value parameter.
Object-Oriented Programming

11

Review of Last Year (C-strings)


In C++ a c_string is a null-terminated character array. C_strings
end with the null character or \0.
cin will read input only up to the first space character. You use the
getline member function to overcome this problem:
cin.getline(name, 30);
This will read input either until 30 characters have been read or
until the new_line has been read.
cin.getline(name, 30, delim_char)
This version will read either until 30 characters have been read or
until new_line has been read or until the delim_char has been read.
The library function strlen( char *str) returns the length of
str minus 1. strcmp(char *str1, char str2) returns 0 if
str1 and str2 are equal, returns a positive number if str1 > str2
and returns a negative number if str1<str2.
Object-Oriented Programming

12

Review of Last Year (File I/O 1)


You use file streams for input/output of data to files. ifstream for
input and ofstream for output to a file. For example:
main()
{
ofstream out;
out.open(text.txt);
char str[20];
out<<Write this sentence to text.txt file<<endl;
out.close();
ifstream in(text.txt);
//note this syntax
in>>str;
cout<<str;
//will output Write on screen
in.close();
return 0;
}
Object-Oriented Programming

13

Review of Last Year (File I/O 2)


When you open a file using the open member function the default
mode is to create the file if it does not exist, or delete it if
something does exist in it. You can control how a file is opened by
passing extra parameters to the open function:
ios::app - opens the file, and allows additions at the end
ios::trunc - deletes everything in the file
ios::nocreate - does not open if the file must be created
ios::noreplace - does not open if the file already exists

For example:
ofstream out(text.txt, ios::app);

Of course, these mode specifiers apply to both input and output


file streams.
Object-Oriented Programming

14

Some Basics
A computer system consists of both hardware and software. The
hardware part is the visible parts of the computer like the monitor,
the keyboard, the CPU chip, memory chip etc. The software part
is invisible to you and includes system programs, user applications,
data etc.
For a computer to do useful tasks, or to do anything at all, it must
be given instructions. A series of instructions which a computer can
execute to perform a useful task is called a program.
Most useful programs need both input and output. Input is the
data/information that the user supplies to the program while it is
running; output is the data/information that the program supplies
or produces for the user.
Object-Oriented Programming

15

Some Basics 2
You can write programs in different ways and at different levels.
Low level programs, those written with low-level languages or the
machine language, are written using binary/octal/hexadecimal
instructions and data. These programs are very hard to write and
are only written for some special operating system features and
other low level systems.
Assembly language programs are programs which are easier to write
than machine language programs but even these are quite
cumbersome to write and writing even a simple addition program
would take many lines of code to complete.
High level programs written in high level languages like C++ and Java
are easier to read and to write. The higher level a program/
programming language is the farther it is from the machine language.
Object-Oriented Programming

16

Some Basics 3
Programs written in low level languages are understandable by the
computer and therefore do not need a translation process. Assembly
language programs are close to machine language but they do need
to be translated to machine language as they are not understandable
by the computer. Assemblers are programs which translate from
assembly language to machine language.
Programs written in high level languages are very far from machine
language. A compiler is a program that translates a high-level
language such as C++ into a machine or low-level language.
Source code is the program that the programmer writes and is ready
to be compiled. Object code is the machine language program that
the compiler produces. Lower level languages are faster because
they are closer to machine language.
Object-Oriented Programming

17

Enumeration Data Type


An enumeration type is a type whose values are defined by a set of
constants of type integer. Lets look at an example:
enum direction { north, east, south, west};

Here we have declared direction to be an enumeration data type


whose only values are north, east, south and west. The above
declaration is equivalent to
enum direction {north=0,east=1,south=2,west=3};

But you can specify different values for each constant as in


enum direction {north=11,east=21,south=31,west=41};

You declare a variable of type direction as follows:


direction dir=west; //declare dir and initialise it

Enumeration types are not used very often but can sometimes make
your code easier to understand.
Object-Oriented Programming

18

Command Line Arguments 1


You know that every C++ program must have a function called main.
Its full definition is
int main(int argc, char *argv[])
The integer argc is the number of arguments including the programs
name. argv is a pointer to an array of character pointers. Each

element in this array points to a command line argument. All


command line arguments are strings; any numbers will have to be
converted into corresponding numerical values. Example:

main(int argc, char *argv[])


{
if(argc !=2) {
cout<<You forgot to type your name.\n;
exit(1); }
cout<<Hello <<argv[1]<<endl;
//second argument
}
Object-Oriented Programming

19

Command Line Arguments 2


In this example we will write a program to open and display a file
on the screen. You specify the file name on the command line.
main(int argc, char *argv[])
{
if (argc != 3)
{
cout<<Incorrect number of arguments<<endl;
exit(1); }
ifstream in(argv[1]);
//open file
char c;
while (!in.eof())
{
in.ge(c);
cout.put(c); }
for (int k=0; k<atoi(argv[2]); k++)
cout<<\a; //atoi is defined in stdlib.h
}
//beeps n times, n is argv[2]

You can specify as many command line arguments as you like.


Object-Oriented Programming

20

Formatting Output
Every output stream has a number of member functions used to
format the way data is output. We know three of them already:
out_stream.setf(ios::fixed);//ordinary real format
out_stream.setf(ios::showpoint);//show point
out_stream.precision(2);
//set precision to 2

There are more output stream member functions such as:

out_stream.setf(ios::showpos);//show plus sign


out_stream.width(4);
//set field widths

Example:

void roottable()
{
int i;
cout.precision(3); cout.setf(ios::fixed);
cout.setf(ios::showpoint);
fot(i=1; i<100; i++)
cout<<setw(4)<<i<<setw(7)<<sqrt(i)<<endl;
}
Object-Oriented Programming

21

Function Overloading
In C++ its possible to have more than one function with the same
name provided the functions have different parameter types or
different number of parameters. This is known as function
overloading. (Having only a different return type is not enough)
Function overloading should be used in situations where we have
functions that do similar tasks. For example, to find the average of
some numbers as in:
int average(int a, int b);
int average(int a, int b, int c);
double average(double a, double b);

Here we have overloaded three functions. When we call one of the


three functions, the compiler knows which function to call. This can
make large programs easier to read and reduces complexity.
Object-Oriented Programming

22

Inline functions
A program that has many function calls can slow down the process of
program execution. This is because calling functions is an expensive
operation and incurs a lot of overhead.
In C++ its possible to define functions that are not called but are
expanded inline at the point of function call. Their advantage is that
they have no overhead associated with the function call and return
mechanism. This means that inline functions can be executed faster.
Only small functions should be defined inline; if the a function is too
large and called too often, then it will make your program grow in
size and this is a disadvantage of inline functions.
inline bool even(int n)
{
return (n%2==0);
}
Object-Oriented Programming

// a small function

23

Object-Oriented Programming 1
Object-oriented programming is a new way of programming. Since
its early days, programming has been practiced using a number of
various methodologies. At each new stage, a new approach was
created to make programming easier and help the programmer
handle more complex programs.
At first, programmers had to write programs using laborious binary
instructions and data with switches. Later, assembly languages were
invented which allowed longer programs to be written.
In the 1950s the first high-level language (Fortran) was invented.
Using a high-level language like Fortran, a programmer could write
a program with several thousand lines of code. But that method
only allowed for unstructured programs: programs without any
structure and very ad hoc.
Object-Oriented Programming

24

Object-Oriented Programming 2
Later in 1960s, the need for structured programs became clear and
languages like Algol, Pascal and C were introduced. C++ invented in
early 1980s is also a structured language; it also supports objectoriented programming.
Structured programming relies on control structures, code blocks,
procedures or functions and facilitates recursion.
The main characteristic of structured programming is breaking
programs into smaller parts. This in turn will help to write better,
more structured and larger programs.
Using structured programming an average programmer can write and
maintain programs that are up 40,000-50,000 lines of code long.
Object-Oriented Programming

25

Object-Oriented Programming 3
With structured programming you can write quite complex programs.
But after a certain point even structured programming or becomes
very hard to follow.
To write larger and more complex programs, a new programming
approach was invented: object-oriented programming or OO for
short. Object-oriented programming combines the best features of
structured programming with some new powerful concepts that
allows writing more complex and more organized programs.
The main new concepts in OO are encapsulation, polymorphism and
inheritance. Any programming language that supports these three
concepts is said to be an OO programming language. Examples of
OO programming languages are C++, Java, Smalltalk. Unlike C++,
Java is a pure OO programming language.
Object-Oriented Programming

26

Object-Oriented Programming 4
Object-oriented programming encourages programmers to break
problems into related subgroups. Each subgroup becomes a
self-contained object with its own instructions and data. So OO
programs consist of objects. An object is similar to an ordinary
variable but with its own member functions.
Writing large programs is made a lot easier using objects. Each
object is a self-contained entity. It is an autonomous entity that
can be used and reused in other programs. This also allows for
composition of objects to create more complex programs.
Its like the automobile manufacturing business where factories
compose new cars out of pre-built parts (objects). These parts or
objects may be manufactured by different companies.

Object-Oriented Programming

27

Encapsulation
Encapsulation is the binding together of code and data and keeping
both safe from outside interference and misuse. When code and
data are bound together like this an object is created.
Inside an object, code and data may be private or public to that
object. Private data or code is known and accessible to other
parts of the object only. So other parts of your program cannot
access the private data or code of an object without permission
from the object. The object dictates or determines how its private
data and functions (code) should be accessed and used.
When code or data is public to an object, then it is possible for
other parts of your program to access that code/data in the normal
way. Usually, the public code of the object is used to provide a
controlled way of accessing the private parts of the object.
Object-Oriented Programming

28

Polymorphism
Polymorphism is the mechanism which allows one name to be used for
two or more related but technically different purposes. Earlier on we
saw overloading of functions which is an example of polymorphism.
As an example, in the C language there are 3 different functions for
finding the absolute value of a number: abs(), labs() and fabs() for
integer, long and float numbers respectively. In C++ you can use
function overloading and use the same name for all the 3 functions
thereby reducing complexity.
The general concept of polymorphism is one interface, multiple
methods. In other words, you use the same method or mechanism
to perform a group of related tasks. As we saw with function overloading, polymorphism helps reduce complexity. Polymorphism can
be applied on both functions and operators as we will see later.
Object-Oriented Programming

29

Inheritance
Inheritance is another important feature of OO programming. With
inheritance an object can acquire or inherit the properties of
another object. The object that inherits another object acquires
all the properties of the parent object and can add its own extra
features specific only to itself.
Inheritance provides for hierarchical classification which is very
important in making information manageable. For example, a square
is a kind of rectangle; in turn, a rectangle is a kind of closed
geometric shape; in turn, a closed geometric shape is a kind of
geometric shape. In each case, the child object inherits all the
properties of the parent object and adds some extra features
specific to itself.
Inheritance is probably the most characteristic feature of OO
programming and its very important.
Object-Oriented Programming

30

The string class 1


C++ has two ways of handling strings. The first, which you saw last
year, is using the traditional null-terminated character arrays. They
are also called c-strings because they were inherited from the C
language. The second way, is using the new standard library string
class. The string class is a new data type which you can use to handle
text strings like c-strings we saw earlier.
When programming c-strings you had to be extra careful about
c-string sizes, the special character \0 and about array operations
such as boundary errors.
With the new standard string class you can do everything you could
do with c-strings and much more. Further, using the string class is
much easier and safer than using c-strings.
Object-Oriented Programming

31

The string class 2


You can still use the c-strings in your programs as they are more
efficient than using the string class. But when you want ease of
use, safety and integration into C++ you should use the new strings
of type string.
Variables of type string are called objects, which means that they
have both data and operations (functions) associated with them. To
use the string class you need to include the header file <string> in
your program. You declare variables (objects) of type string as in:
string str1, str2(Hello), str3(str2);

There are three ways of declaring objects of type string as you can
see above. The first creates an empty string object, the second
creates and initializes a string object and the third one creates
a string object from another string object.
Object-Oriented Programming

32

The string class 3


You can check two string objects for equality the same way you
check other variables of built-in types:
bool equal(string str1, string str2)
{
return str1==str2;
}

You can also concatenate two string object:


string str1(Hello), str2(World), str3;
str3=str1 + + str2;

You can assign one object to another:


string str1(Spring), str2(Summer);
str1=str2;
This is not only a lot easier and more intuitive but safer than using
strcmp, strcpy and strcat functions with c-strings.
Object-Oriented Programming

33

The string class 4


You can use the << and >> operators to perform input and output. For
example:
main()
{
string first_name,last_name, full_name;
cout<<Enter your first and last name: ;
cin>>first_name>>last_name;
full_name=first_name + + last_name;
cout<<You full name is <<full_name<<endl;
cout<<Your last name is spelled: ;
for(int i=0; i<str2.length(); i++)
cout<<last_name[i]; //last_name.at(i)
string str4;
cout<<Enter your full name;
getline(cin, str4);
cout<<Hello +str4<<endl;
}
Object-Oriented Programming

34

The string class 5


As you can see, string objects are more flexible than c-strings. You
can use the subscript operators [] for accessing string characters
in string objects but there is a better way of doing this. To access a
specific character of a string object just use the at() member
function which is safer than [] operators. (see the comment on 31)
Look at the following two fragments of code:
string str(Dean);
cout<<str[6];

string str(Dean);
cout<<str.at(6);

For the first version the compiler might not give an error message
although it should, but in the second version will terminate the
program so you know something is wrong.
Also note the standalone function getline() which is similar to the
input stream getline() but works with string objects only.
Object-Oriented Programming

35

The string class 6


Lets look at an example program that checks to determine whether
a string of text is a palindrome or not:
#include <iostream>
#include <string>
using namespace std;
void swap(char &a, char &b);
//swap two chars
bool isPal(const string &str);
//check if pal.
string reverse(const string &str);
//reverses strings
main()
{
string str;
getline(cin,str);
cout<<str<<endl;
if(isPal(str))
cout<<"(\")"<<str + "\" is a palindrome";
else
cout<<"\""<<str + "\" is not a palindrome"; }
Object-Oriented Programming

36

The string class 7


You know how to define the swap() function so there is no need to
redefine it here. The reverse() function takes as parameter a
reference string, finds the reverse of the string and returns that
reversed string. The boolean isPal() function merely checks to
see if the original string is equal to the reversed string. Note that
it uses the reverse() function in its body.
The standard string class has hundreds of functions and you can
look them up in the MSDN library installed in the labs. Some of the
most useful functions are:
str1.substr(pos, length);
//returns sub-string of str1 starting
//at position for length characters(read-only)
str1.at(i);
//returns the str1 char with index i (read/write)
Object-Oriented Programming

37

The string class 8


More string functions:
str1=str2;

//allocate space and initialize str1 to


//str2s data
str1+=str2; //data of str2 is concatenated to the
//str1 end of
str1.empty(); //returns true if str1 is empty, false
//otherwise
str1+str2;
//returns a string that has str2s data
//concatenated to the end of str1
str1.insert(pos, str2);

//insert str2 into str1 at


//position pos
str1.erase(pos, len);
//remove sub-string of len
//starting at position pos
str1==str2
str1 != str2 //compare for equality or
//inequality
Object-Oriented Programming

38

The string class 9


more string functions:
str1<str2
str1<=str2

str1>str2 //lexicographical comparisons


str1>=str2 //lexicographical comparisons

str1.find(str2);

//returns index of first


// occurrence of str2 in str1
str1.find(str2, pos);
//same as above but search
// starts at position pos
str1.replace(start, num, str2)
//beginning at
//start, replace num chars with str2

As you can see there are many string functions and there are many
more but we will only be using the above for most of the time.
Also note that since a string is treated as a data type you can have
an array of strings as in:
string names[31];
Object-Oriented Programming

39

The string class 10


An example program demonstrating some string functions:
main()
{
string str1(String handling in C++);
string str2(STL Power);
str1.insert(6, str2);
//put str2 in str1
cout<<str1<<endl;
str1.erase(6, 9);
//erase 9 chars
cout<<str1<<endl;
str1.replace(7, 8, str2); //replace 8 chars with str2
cout<<str1<<endl;
}

This program would output the following:


StringSTL Power handling in C++
String handling in C++
String STL Power in C++
Object-Oriented Programming

40

Exercises
1. Write a program to display a numbered menu on the screen such
as:
*****************************************
* Welcome!
*
* 1. Display Todays Date
*
* 2. Display Time
*
* 3. Display Both Time and Date
*
* 4. Exit
*
* Enter a number 1 4:
*
*****************************************

In response to the users selection, the program should invoke a


function to perform the required action. You can use system calls
to obtain time and date, for example
system(date);

will display the computers date on the screen.


Object-Oriented Programming

41

Exercises
2. Write a function that takes two integer arrays, of equal size, as
parameters. The function asks the user to fill the first array with
a mixture of positive and negative numbers. Then your function
should separate the positives from the negatives and write them
into the second array. The positives should go to the lower-indexed
locations and the negatives should go into the higher-indexed cells.
3. What does the following program do:
main()
{
char names[5][20];
for (int i=0; i<5; i++)
cin>>names[i];
for ( i=0; i<5; i++)
cout<<names[i]<<endl;
}
Object-Oriented Programming

42

Exercises
4. Using c-strings, write a program that asks the user to type in
10 words. The program should then display all the 10 words in
alphabetical order and also display the shortest and longest words.
(hint: see exercise 3)
5. Redo exercise 4 using the Standard String Class.
6. Write a program that takes two command line arguments. Save
the program as find.cpp. The first argument is a word of type
(c-string or string object) and the second argument is a filename.
The program must open the specified file and search for or find all
the occurrences of the specified word in that file. It should print
the number of occurrences of that word and if the word is not
present in the file an appropriate message should be displayed.
7. Explain what is encapsulation? polymorphism? inheritance?
Object-Oriented Programming

43

Exercises
8. Write a program that will read in a sentence from the keyboard.
The output of your program should be the same sentence but with
spacing corrected, for example the following sentence
Never

re-invent

should be output as

the

wheel.

Never re-invent the wheel.

9. Write a program that will attempt to open a file; then it asks


the user for a word and displays the number of occurrences of that
word in the file on the screen.
10. Write a program that reads in a line of text and replaces all
four-letter words with the word like, for example
I do not hate your dog. Should be output as
I do not like like dog.
Object-Oriented Programming

44

Exercises
11. Write a function that takes a string array as parameter and
it should sort the elements of the array into alphabetical order.
Test your function in a driver program.
12. What would be the output of each of the following functions if
called with name as their parameter:
char name[]=Mr Nice;
void Print(char name[])
{
cout<<Name: <<name<<endl;
}
void Print(char *name)
{
cout<<Name: <<name<<endl;
}
Object-Oriented Programming

45

Exercises
13. Suppose you have two functions as follows:
double answer(double num1, double num2);
double answer(double num1, int num2);

which function would be used in the following function call and why?
(x and y are of type double)
x=answer(y, 6.0);

14. In C, there are 3 functions for obtaining the absolute value of


numeric values, one for integers (abs()), one for longs (labs())
and one for floats (fabs()). Using function overloading write 3
functions for determining the absolute value of an integer, long
integer and a double. Call your 3 functions abs and test your
functions in a driver program.
Object-Oriented Programming

46

Classes
A class is a data type whose variables are objects. The class is
probably the most important feature of C++. Classes are used to
create objects. A programming language must support classes if it
is to be object-oriented. The syntax of a class is as follows:
class class-name
{
private functions and variables of the class
public:
public functions and variables of the class
};

Class declarations are similar to structure declarations. Classes


define new data types so class-name above is a new type which
you can use in your programs to declare objects of this new type.
Functions and variables declared inside a class are members of that
class: member functions and member variables.
Object-Oriented Programming

47

Classes 2
By default, all member functions and variables declared inside a
class are private to that class. This means that they are accessible
only by other members of that class. Other parts of your program
cannot directly access them. Public member functions and variables
are accessible by both other parts of the class and by other parts
of your program. Lets look at an example:

class myclass
{
int a;
//private member variable
public:
//notice the colon :
void set_a(int num);
//public member functio
int get_a();
//public member function
};

Note: a is a private member and is not accessible outside myclass.


Object-Oriented Programming

48

Classes 3
Now we will define the member functions of the class myclass:
void myclass::set_a(int num)
{
a=num;
}
int myclass::get_a()
{
return a;
}

Because both set_a() and get_a() have access to a, they can


directly access it. Now that we have a class defined, we can create
objects from it:
myclass ob1, ob2;
Two successive colons is called the scope resolution operator.
Object-Oriented Programming

49

Classes 4
Now we will write a complete program that uses the class myclass:
//must include class definition here
main()
{
myclass ob1, ob2;
ob1.set_a(10);
ob2.set_a(20);
cout<<ob1.get_a()<<endl;
cout<<ob2.get_a()<<endl;
//ob1.a=11;
return 0;

//this would be illegal

As you should expect the output would be 10 followed by 20.


Object-Oriented Programming

50

Constructors
Your programs variables usually require initialization. Sometimes
initialization is absolutely necessary and sometimes its not, but its
always a good idea to initialize your variables. With objects too, you
should use initialization. In fact, most objects require some sort of
initialization before you can make any use of them.
A constructor is used to do automatic initialization for objects. A
constructor is a special member function that is called automatically
whenever an object is created or instantiated. For example:
class myclass
{
int a;
public:
myclass();
void show();
};
Object-Oriented Programming

//turn over

51

Constructors 2
continued
myclass::myclass()
{
cout<<In constructor\n;
a=0;
}
void myclass::show()
{
cout<<a<<endl;
}
main()
{
myclass ob; //constructor called
ob.show();
//will output 0
return 0;
}
Object-Oriented Programming

52

Constructors 3
Note that the constructor myclass has the same name as the class
it is part of and has no return type. Its a special function that is
called only when an object is created or declared. It cannot be
called any other time. Also note that for global objects the
constructor function is called only once while for local objects it may
be called many time.
Its also possible to have parameterized constructor functions:
(from previous example)
myclass::myclass(int x)
{
cout<<In Constructor\n
a=x;
}
myclass ob(0);
ob.show();
//will output 0
Object-Oriented Programming

53

Destructors
An objects constructor is called when the object is first created.
When an object is destroyed its destructor is called. Sometimes
its necessary to do some things after we finish with an object such
as freeing heap memory or deleting pointers and such. You could do
these tasks in a destructor function that is called automatically
when the object goes out of scope: end of program, end of function
call. The name of a destructor is the name of the class it is part of
preceded by a ~:
class myclass
{
int a;
public:
myclass();
~myclass();
void show();
};
Object-Oriented Programming

turn over

54

Destructor 2
continued
myclass::myclass(){
cout<<In constructor\n;
a=10;
}
myclass::~myclass()
{
cout<<In Destructor\n
}
void myclass::show(){
cout<<a<<endl;
}
main()
//run the program in the lab
{
myclass ob;
ob.show();
}
Object-Oriented Programming

55

An Example
Now we will look at an example that demonstrates the use of both
constructors and destructors:
#include <iostream> #include <string>
#include <stdlib>
using namespace std;
const int SIZE=255;
class strtype
{
char *p;
int len;
public:
strtype();
~strtype();
void set(char *p);
void show();
};
Object-Oriented Programming

56

An Example 2
continued
strtype::strtype()
{
p=new char(SIZE);
if(!p) {
cout<<Allocation error\n;
exit(1);
}
*p=\n;
//same as p[0]=\n
len=0;
}
strtype::~strtype()
{
cout<<Freeing memory\n;
delete p;
}
Object-Oriented Programming

57

An Example 3
continued
void myclass::set(char *ptr)
{
if(strlen(ptr)>SIZE)
{
cout<<String too big;
return;
}
strcpy(p, ptr);
len=strlen(ptr);
}
void myclass::show()
{
cout<<p<< length: <<len<<endl;
}
Object-Oriented Programming

58

An Example 4
main()
{
strtype s1, s2;
s1.set(This is a test);
s2.set(I like C++);
s1.show();
s2.show();
return 0;
}

In this example, we saw a use of constructors and destructors in


allocating and freeing dynamic memory. Doing this will relieve the
programmer form performing initializations for every new object
created: initialization and freeing up memory are done automatically
whenever a new object is declared. This is very important as it
helps reduce complexity.
Object-Oriented Programming

59

Another example
This is an interesting example in which we will use an object of type
timer class to time the interval between when an object of type
timer is created and when it is destroyed. When the objects
destructor is called, the elapsed time,in seconds, is displayed on the
screen. An example of the use of this timer class is that you could
use it to time the duration of your programs.
#include <iostream>
#include <time.h>
class timer
{
clock_t start;
public:
timer();
~timer();
};
Object-Oriented Programming

60

Another example 2
continued
timer::timer() {
start=clock();
//get time
}
timer::~timer() {
clock_t end;
end=clock();
cout<<Elapsed time: <<(end-start)/CLK_TCK<<endl;
}
//divide by clock ticks
main()
{
timer ob;
char c;
cout<<Press a key followed by ENTER:;
cin>>c;
}
program duration displayed in seconds
Object-Oriented Programming

61

Object Pointers
As you have seen, you can access members of an object using the dot
operator. You can also use pointers to objects to access their
member functions as shown in this example:
class myclass
{
int a;
public:
myclass(int x);
int get();
};
myclass::myclass()
{
a=x;
}
int myclass::get()
{
return a;
}
Object-Oriented Programming

62

Object Pointers 2
continued
main()
{
myclass ob(100);
myclass *p;
p=&ob;
cout<<Value using dot operator: <<ob.get()<<endl;
cout<<Value using pointer to ob: <<ob->get()<<endl;
return 0;
}

Notice that declaring a pointer to a class does not create an object.


It just creates a pointer that could point to an object of that class.
In line 3 above, we set a pointer to point to an object that we have
already created.
Object-Oriented Programming

63

Inline Functions in Classes


In-line functions are expanded at the place where they are called.
Only short functions should be made in-line. You specify a member
function as in-line by preceding the function definition by the word
inline:
inline myclass::get() {
return a;
}

If you include a functions definition inside the class declaration,


that function is in-line. This is called automatic in-lining. In this
case the word in-line is optional:
class myclass
{
int a;
public:
int get() {return a; }
};
Object-Oriented Programming

64

Exercises
15. Create a class called card that maintains information on nooks.
The class should store the books title, author, year and number of
copies on hand. Use a public member function store() to store a
books information and public member show() to display book information. Test your class in a driver program.
16. When is a constructor function called? When is a destructor
function called?
17. There are two ways for making a function expand in-line. What
are they?
18. Some restrictions on in-line functions: (true or false)
a) the function must be short
b) the function must be defined before it is first used
c) It may not include loops
d) It must not be recursive
Object-Oriented Programming

65

Exercises
19. You can have overloaded constructor functions as the following
class definition demonstrates:
class myClass{
int x;
char c;
public:
myClass();
myClass(int x, char c);
};

Which of the following are legal?


a)
b)
c)
d
e)
f)

myClass ob1(2, h);


myClass ob2;
myClass ob3();
ob1=myClass(6, g);
ob1=myClass();
ob1=myClass;

Object-Oriented Programming

66

Exercises
20. Define a class called BankAccount. Declare the following private
data members:
- Customer No.
- Customer Name
- Customer Address
- Account Opening Date
- Balance
also declare the following member functions for your class:
- A constructor to initialize private data members, name, no.,
- Member functions to set and get account information
- A member function to update an accounts balance
- A member function to print a customers info on the screen
Then test you class in a driver program.
Object-Oriented Programming

67

Assigning Objects
You can assign one object to another object only if they are both of
the same type. When an object is assigned to another object a
bit-wise copy of all the data members is performed. Example:
class myclass
{
int a, b;
public:
void set(int i,int j) {a=i; b=j;} //automatic in-lining
void show() {cout<<a<< <<b<<\n;}
};
main()
{
myclass ob1, ob2;
o1.set(3, 8);
o2=o1; //assign o1 to o2, copies data members a and b
o1.show();
//will output:
3 8
o2.show();
//will output:
3 8
}
Object-Oriented Programming

68

Assigning Objects 2
But assigning objects can be dangerous sometimes. Can you identify
the problem with this example:
class mystring
{
char *p;
int len;
public:
mystring(char *ptr);
~mystring();
void show();
};
mystring::mystring(char *ptr)
{
len=strlen(ptr);
p=new char[len+1];
if(!p) {
cout<<Allocation error\n; exit(1); }
strcpy(p, ptr);
}
Object-Oriented Programming

69

Assigning Objects 3
mystring::~mystring()
{
cout<<Freeing p\n;
delete p;
}
void mystring::show() {
cout<<p<< length: <<len<<endl;
}
main()
{
mystring s1(This is a test), s2(I like C++);
s1.show();
s2.show();
s1=s2;
s1.show();
s2.show();
}
Object-Oriented Programming

70

Assigning Objects 4
The problem with this program is that both s1 and s2 need to
obtain memory from the heap. A pointer to each objects allocated
memory is stored in p. When a mystring object is destroyed, this
memory is released.
But when s1 is assigned to s2, both objects pointers point to the
same memory segment. When they are destroyed the memory
pointed to by s1 is freed twice while the memory originally pointed
to by s2 is not freed at all.
Although it may not be as drastic in this small program, this type of
error is very insidious and can do damage to the dynamic memory
and may cause your programs to crash. You should be extra careful
when using dynamic memory in class constructors and destructors.
Object-Oriented Programming

71

Objects to functions
You can pass objects as parameters to functions. As with other
types of data, by default all objects are passed by value.
class myclass {
int i;
public:
myclass(int n) { i=n;}
int get_i() { return i;}
};
int sqr_it(myclass ob) {
return ob.get_i() * ob.get_i();
}
main()
{
myclass ob1(10);
cout<<sqr_it(ob1);

//will output 100

}
Object-Oriented Programming

72

Objects to functions 2
Objects are passed to functions by value. To have functions modify
the actual objects passed, the objects address must be passed:
class myclass {
int j;
public:
myclass(int n) { j=n;}
int get_j() {return j;}
void set_j(int n) {j=n;}
};
void sqr_it(myclass *o) {
o->set_j(o->get_j() * o->get_j());
}
main()
{
myclass ob(10);
sqr_it(&ob);
cout<<ob.get_j();
}
Object-Oriented Programming

73

Objects to functions 3
When an object is passed to a function, a temporary copy of that
object is made which means that a new object comes into existence.
And when that function terminates, the copy of the passed object is
destroyed. Two questions:
1. Is the objects constructor called when the copy is made?
2. Is the objects destructor called when the copy is destroyed?
Think carefully about these questions before answering them. When
a copy of an object is made to be used in a function call, the objects
constructor is NOT called. Because constructor functions are usually
called when initialization needs to be done to the objects data. When
we pass an object to a function we dont want to lose the data or the
state the object had before being passed to the function. You want
the function to work on the object as it is not on its initial state.
Object-Oriented Programming

74

Objects to functions 4
On the second question, the answer is that when the function ends,
or when it is destroyed, the objects destructor IS called. This
makes sense because the object may do something that needs to be
undone before going out of scope when the function returns. For
example, the object may acquire dynamic memory that needs to be
released before the object is destroyed. The following example
shows what happens when an object is passed to a function:
class myclass
{
int i;
public:
myclass(int n) {
i=n;
cout<<Constructing\n; }
~myclass() { cout<<destructing\n; }
int get_i() {return i;}
};
Object-Oriented Programming

75

Objects to functions 5
continued
int sqr_it(myclass ob)
{
return ob.get_i() * o.get_i();
}
main()
{
myclass ob(5);
cout<<sqr_it(ob)<<endl;;
}

The output is:

Constructing
Destructing
25
Destructing

Only one call to the constructor is made. However, two calls to the
destructor are made, one for the objects copy and one for itself.
Object-Oriented Programming

76

Objects to functions 6
The fact the destructor of an object, passed to a function, is called
when the function terminates can cause some problems. For example
if the object allocates dynamic memory and releases that memory
when destroyed, then the objects copy will free the same memory
when its destructor is called. This will leave the original object
damaged. It is important to protect against this kind of problem.
One way for resolving this issue is by passing the address of object
to functions. Since the address of the object is passed, no copying
of objects carried out and therefore no destructor is called.
There is an even better solution that uses a special type of
constructor called a copy constructor. A copy constructor allows
you to specify how copies of objects are made. We will cover copy
constructors later on.
Object-Oriented Programming

77

Objects to functions 7
We will now look at an example that illustrates the problems that
can arise when dealing with objects passed to functions:
class dynamic{
int *p;
public:
dynamic(int I);
~dynamic(){ delete p; cout<<Freeing memory\n;}
int get() { return *p;}
};
dynamic::dynamic(int i)
{
p= new int;
if(!p) {
cout<<Allocation failure\n;
exit(1); }
*p=i;
}
Object-Oriented Programming

78

Objects to functions 8
continued
int negative(dynamic ob)
{
return ob.get();
}
main()
{
dynamic ob1(-8);
cout<<ob1.get()<<endl;
cout<<negative(ob1)<<endl;
cout<<ob1.get()<<endl;
//error
cout<<negative(ob1)<<endl; //error
}

Here, ob1s destructor is called when the function negative ends and
this causes the dynamic memory pointed to by the original ob to be
destroyed.
Object-Oriented Programming

79

Returning Objects from Functions


As you can pass objects to functions, you can also have functions
that return objects. Just declare the function as returning a
class type as in:
class myclass {
int i;
public:
myclass(int n) { i=n; cout<<Constrcuting\n}
~myclass() {cout<<Destructing\n;}
int get() { return i;};
};
myclass myfunction()
{
myclass ob(9);
return ob;
}
Object-Oriented Programming

80

Returning Objects from Functions 2


continued
main()
{
myclass ob(0);
ob=myfunction();
cout<<ob.get();
}

If you try this program in the lab, you will see that 2 constructor
calls and 3 destructor calls are made. The third destructor call is
made when the object is returned from the function. A temporary
object is made which is returned by the function; it is the copy of
this object whose destructor is called. Again as with objects passed
to functions, this situation can also cause problems. And again the
solution for this problem lies in using a copy constructor which we
will study shortly.
Object-Oriented Programming

81

Friend Functions
In some situations you may need a function that has access to the
private members of a class without that function being a member of
that class. A function that has this property is called a friend
function. There are a number of uses of friend functions which we
will see later. One of the uses is when you want a function that has
access to the private members of two or more different classes.
A friend function is defined like regular, non-member functions as
the example below demonstrates:
class myclass
{
int n, d;
public:
myclass(int i, int j) {n=i; d=j;}
friend bool isFactor(myclass ob); //notice this
};
Object-Oriented Programming

82

Friend Functions 2
bool isFactor(myclass ob)
{
if (!(ob.n % ob.d))
return true;
else
return false;
}
main()
{
myclass ob(8, 4);
if(isFactor(ob)) cout<<4 is a factor of 8\n;
else cout<<<<4 is a not factor of 8\n;
}

Notice how friend functions are declared. They are defined just
like regular functions. But you need to declare them in the class to
which the function will be a friend and precede the declaration with
the keyword friend.
Object-Oriented Programming

83

Friend Functions 3
A friend function can only access a classs private members if it has
been passed an object of that class or if an object of that class has
been declared inside the function. A friend function cannot directly
access a classs private members.
Note that since a friend function is not a member function it is
not defined using the scope resolution operator; also is not qualified
by an object name.
One other important point about friend functions is that a friend
function may be friends with more than one class. We will show this
in the next slide program. Here we define two classes and define a
friend function to access private members of the two classes. Note
how a forward reference is made. A forward reference is needed
because one class is referred to by another while being defined.
Object-Oriented Programming

84

Friend Functions 4
class truck;
//forward reference
class car
{
string model;
int speed;
public:
car(string m, int s) {model=m; speed=s;}
friend bool faster(car c, truck t);
//car > truck
};
class truck
{
int weight;
int speed;
public:
truck(int w, int s) {weight=w; speed=s;};
fried bool faster(car c, truck t);
};
Object-Oriented Programming

85

Friend Functions 5
int faster(car c, truck t)
{
return c.speed > t-speed;
}
main()
{
car c(Mazda, 140);
truck t(5000, 120);
if(faster(c, t))
cout<<Car c is faster than truck t\n;
}

A function can be a member function of a class and a friend of


another class. When declaring such a function you need to use the
scope resolution operator as it is a member function. But in the
class to which it is a friend you need to specify that the function
is defined as a member function of another class as in:
friend bool car::faster(truck t);
Object-Oriented Programming

86

Exercises
21. When an object is assigned to another object, what does exactly
happen?
22. When an object is passed to a function, a copy of that object
is made inside the function; is the copys constructor called? Is the
copys destructor called when the function returns?
23. Explain what undesired side effects may happen when passing
objects to functions and returning objects from functions.
24. What is a friend function and give two situations in which using
friend functions can be useful?
25. What is the difference between a friend function for a class
and a member function of a class?
Object-Oriented Programming

87

Copy Constructors
Recall that when
1. an object is assigned to another object or when
2. an object is used to initialize another object or when
3. an object is passed to a function as a parameter or when
4. an object is returned from a function
a bit-wise copy of the object is made and we saw this can cause
problems especially when using pointers and dynamic memory.
Well, a copy constructor can be used to solve the problem for the
last three cases above; for the first we will need to overload
the assignment operator to resolve the problem.
Note that the last three cases above are examples of initialization
while the first case is an assignment operation.
Object-Oriented Programming

88

Copy Constructors 2
Copy constructors have the following general form:
classname( const classname &obj)
{
//body of constructor
}
Here, obj is a reference to the object that is being used to initialize
another object. We use a copy constructor in the following example:
class array
{
int *p;
int size;
public:
array(int sz) { p=new int[sz]; if(!p) exit(1);
size=sz; cout<<Normal constructor<<endl; }
~array() { delete [] p;}
Object-Oriented Programming

89

Copy Constructors 3
//copy constructor
array(const array &obj);
void put(int i, int j) {
//boundary check
if(i>=0 && i<size) p[i]=j;
}
int get(int i) {
return p[i];
}
array::array(const array &obj) {
int i; p=new int [obj.size];
if(!p) exit(1);
for(i=0; i<obj.size; i++) p[i]=obj.p[i];
cout<<Copy constructor<<endl;
}
Object-Oriented Programming

90

Copy Constructors 4
main()
{
array num(10);
int i;

//calls normal constructor

for(i=0; i<10; i++) num.put(i, i);


for(i=0; i<10; i++) cout<<num.get(i)<<endl
//create another array and initialise with num
array x=num;
//calls copy constructor
for(i=0; i<10; i++) cout<<x.get(i)<<endl;
return 0;
}
Object-Oriented Programming

91

Default Arguments
Default arguments allow you to give a parameter a default value
When no corresponding argument is specified when the function is
Called. Using default arguments is essentially a shorthand form of
Function overloading. Consider the function prototype:
void f(int a=0, int b=0);
this function can be called three different ways:
f();
//a and b default to 0
f(9); //a is 9 and b defaults to 0
f(8, 7); //a is 8 and b is 7
All default arguments must be to the right of any parameters that
dont have defaults, so the following would be illegal:
void f(int a=0, int b); //illegal
Also, you may specify default arguments either in function prototype
or in function definition, not in both ( a C++ restriction)
Object-Oriented Programming

92

Default Arguments 2
Default arguments are related to function overloading as you can
See in the following example:
double box_area(double length, double width) {
return length*width;
}
double box_area(double length) {
return length*length;
}
main()
{
cout<<10 x 5.8 square box has area :;
cout<<box_area(10, 5.8);
cout<<10 x 10 square box has area :;
cout<<box_area(10);
}
Object-Oriented Programming

93

Default Arguments 3
If you think about it, there is really no need to have two different
functions; instead the second parameter can be defaulted to some
value that acts as a flag to the function box_area():
double box_area(double length, double width=0){
if(!width) width=length;
return length*width;
}
main()
{
cout<<10 x 5.8 square box has area :;
cout<<box_area(10, 5.8);
cout<<10 x 10 square box has area :;
cout<<box_area(10);
}
Object-Oriented Programming

94

this
C++ has a special pointer called this. This is a pointer that is
Automatically passed to any member function when it is called and
It is a pointer to the object that generates the function call.
When a member function refers to another member of the class
It does so directly. It does this without qualifying the reference
With a class name or object name. But what is actually happening
Is that that member function is automatically passed a pointer, this,
Which points to the object that generated that function call:
class myclass {
int a;
Public:
void set_a(int x) {a=x;}
int get_a() { return a;}
};
Object-Oriented Programming

95

this 2
main()
{
myclass obj;
obj.set_a(99);
cout<<obj.get_a()<<endl;
}
What is really happening behind the scenes is that the member
functions get_a and set_a are passed a pointer and they use this
pointer to access the private member a:
class myclass{
int a;
Public:
void set_a(int x) { this->a=x;}
int get_a() { return this->a;}
};//you should know this, but uncommon usage
Object-Oriented Programming

96

Exercises
26. What is the default method of parameter passing in C++,
including for objects?
a) By value
b) By Reference
c) Neither
d) Both
27. What is a friend function?
28. Given the class definition below, convert all references to
class members to explicit this pointer references:
class myclass
{
int a, b;
public:
myclass(int n, int m) { a=n; b=m;}
int add() { return a+b;}
void show();}h
Object-Oriented Programming

97

Exercises
void myclass::show()
{
int t;
t=add();
cout<<t<<\n;
}
29. Imagine a situation where two classes, myclass1 and myclass2,
share one printer. Further imagine that other parts of your
program need to know when the printer is in use by an object of
either of these two classes. Create a friend function inuse() that
returns true when the printer is in use by either object or false
otherwise. This function is a friend of both classes.
30. When is a constructor function called? A destructor?
Object-Oriented Programming

98

Exercises
31. Given the declaration of an array of objects as follows:
sample ob[4]={1,2,3,4};
Write the definition of the class sample so that the above
declaration is legal.
32. Add a copy constructor function to the following class
definition:
class strtype{
char *p
public:
strtypr(char *p);
~strtype() { delete [] p;}
char *get() {return p;}
}
Object-Oriented Programming

99

Exercises
strtype::strtype(char *s)
{
int l;
l=strlen(s);
p=new char [l];
if(!p) exit(1);
strcpy(p, s);
}
void show(strtype str)
{
char *s;
s=str.get();
cout<<s<<\n;
}

Object-Oriented Programming

100

Exercises
main(){
strtype a(Hello), b(There);
show(a);
show(a);
show(b);
}
What single condition or prerequisite must be met before an
object can be assigned to another object?
Define a function with the following prototype:
void print (char *p, int how=0);
If the value of second argument is 1 it should print the string in
uppercase form, if it is 2, it should print in lowercase form, if it
is 0 or not specified then the stign should be displayed as it is.
(This is an example of using a default argument as a flag; like
the getline function whose 3rd parameter is a flag)
Object-Oriented Programming

101

Handling Time in C++ (Digression)


The header file <time.h> defines three time-related data types:
clock_t, time_t and tm. The first, clock_t can represent the
system time as some integer. The second, time_t is capable of
representing the system time (and date), again as some sort of
integer. The third, tm is a structure capable of representing both
time and date broken down into their elements. The members of
tm are:
int
int
int
int
int
int

tm_sec;
tm_min;
tm_hour;
tm_mday;
tm_mon;
tm_year;

Object-Oriented Programming

// seconds, 0-60
// minutes, 0-59
// hours, 0-23
// day of month, 1-31
// month since Jan, 0-11
// years from 1900
//see next page

102

Handling Time in C++ 2


int tm_wday;
int tm_yday;
int tm_isdst;

// days since Sunday, 0-6


// days since Jan 1, 0-365
// Daylight Saving Time indicator,
// positive if saving is on, 0 if
// not on, negative if there is no
// information available
In addition, <time.h> defines the constant CLOCKS_PER_SEC which
is the number of system clock ticks per second. The <time.h>
header also defines a number of time-related functions,
including the following:
clock_t clock();
returns a value that approximates the amount of time the calling
program has been running. Divide this by CLOCKS_PER_SEC to
transform this value to seconds.
Object-Oriented Programming

103

Handling Time in C++ 3


time_t time(time_t *time);
returns the current calander time of the system. (can be called
with a null pointer or with a pointer to a variable of type time_t)
char *asctime(const tm *p);
Returns a pointer to a string that contains the information stored
in the structure pointed to by p converted into the following
format,
for example:
Sun Dec 2 09:15:55 2001
tm *localtime(const time_t *t);
returns a pointer to the broken-down form of time in the form of a
tm structure. The time pointer is obtained through a call to
time();
Object-Oriented Programming

104

Handling Time in C++ 4


Lets look at an example involving these functions:
#include <iostream.h>
#include <time.h>
main()
{
time_t t=time(NULL); //get system time
tm *p;
p=localtime(&t);
//convert to tm structure
cout<<p->tm_mday<<" "<<p->tm_mon+1<<" "<<
p->tm_year+1900<<endl;
cout<<asctime(p);
//convert to string
}
The output would be:

Object-Oriented Programming

30 12 2001
Sun Dec 30 09:39:09 2001

105

Operator Overloading
Operator overloading is another important feature of C++ and
object-oriented programming. It allows you to give new meaning
to C++ operators relative to classes that you define.
Operator overloading is similar to function overloading. The same
Way that function overloading helps us write better programs,
Operator overloading also helps you write better programs and
Reduce complexity.
When an operator is overloaded, that operator loses none of its
Original meaning. Instead, it gains additional meaning relative to
the class for which it is defined. To overload an operator, you must
create an operator function. Most often an operator function is a
member function or a friend function. We will first explore
member operator functions then friend operator functions
Object-Oriented Programming

106

Operator Overloading 2
The general form of a member operator function is as follows:
return-type class-name::operator#(arg-list)
{
//operation to be performed
}
Usually the return type is the class for which it is defined. The
operator being overloaded is substituted for the #. For example if
+ is being overloaded then the function name would be operator+.
The contents of arg-list vary depending on how the operator
function is implemented and the type of operator being overloaded.
There are two restrictions that apply to overloaded operators:
the precedence of the operator cannot be changed, second the
number of operands that an operator takes cannot be changed.
Object-Oriented Programming

107

Operator Overloading 3
Most C++ operators can be overloaded: =, ==, <,>,<=,>=,+,-,/,*,<<,>>,!....
When a member operator function overloads an operator, the
Function will have only one parameter. This parameter will receive
The object that is on the right side of the binary operator. The
Object on the left is the object that generated the call to the
Operator function.
Suppose we have a class called coord that represents a coordinates
Point on the plane and we want to overload the + binary operator
For adding two coordinates points:
class coord {
int x, y;
public:
coord() {x=0, y=0;}
coord(int i, int j) {x=i; y=j;}
Object-Oriented Programming

108

Operator Overloading 4
void get_xy(int &i, int &j) {i=x, j=y;}
coord operator+(coord ob2);
};
coord coord::operator+(coord ob2)
{
coord temp;
temp.x=x+ob2.x;
temp.y=y+ob2.y;
return temp;
}
main()
{
int x, y;
coord o1(10, 10), o2(4, 8), o3;
o3=o1+o2;
o3.get_xy(x, y)
cout<<o3 coordinates are: x: <<x<< y: <<y<<endl;
}
Object-Oriented Programming

109

Operator Overloading 5
A few thing to notice about this example:
temp object is needed so our + is consistent with normal use.
The two operands should not be modified in any way, as this is the
case when doing arithmetic: 4+8
The operator+() function returns an object of the same type as
its operands. This is again consistent with the traditional
meaning of the + operator. This will also allow you to have a
series of additions in expressions: o5=p1+o2+o3+o4
because a coord object is returned the following is possible:
(o1+o2).get_xy(x, y);

Lets now overload the assignment operator for the coord class:
Coord coord::operator=(coord ob2){
x=ob2.x;
y=ob2.y;
return *this;//return the object that is assigned
}
//so our = operator is consistent with normal use
Object-Oriented Programming

110

Operator Overloading 6
Overloading a unary operator is similar to a binary operator except
that there is only one operand to deal with. When overloading a
unary operator for a member function, the function has no
parameters. Now we will overload the increment ++ operator relative
to the class coord:
coord coord::operator++()
{
x++;
y++;
return *this;
}
Dont forget that you can also overload relational and logical
operators. Your overloaded operators should have a similar behavior
to the original operators. Following this rule will make your programs
easier to follow and read.
Object-Oriented Programming

111

Operator Overloading 7
We saw on slide 104, how we can overload the + operator relative
to coord class to add two coord objects; so we could do o1+o2;
But if you want the second (right-hand side) operand to be a builtin type, then you would have to overload your +operator:
coord coord::operator+(int i)
{
coord temp;
temp.x=x+i;
temp.y=y.i;
return temp;
}
Now, we can have statements like: o2=o1+2. But we still cannot
have a statement like o2=1+o1, because the left-operand is the
implicit operand passed to the operator function (the right-hand
operator is passed to the function as an argument).
Object-Oriented Programming

112

Operator Overloading 8
The solution to this is using friend operator functions instead. A
friend function does not have a this pointer (only member functions
do) This means that in the case of a binary operator, both operands
must be passed to the function and for unary operators, the single
operand is passed.
The main reason for using friend operator functions is that they
let you mix objects with built-in types, especially when the righthand side is a built-in type ( we could not do this using member
operator functions)
class coord {
int x, y;
public:
coord() {x=0, y=0;}
coord(int i, int j) {x=i; y=j;
Object-Oriented Programming

113

Operator Overloading 9
friend coord operator+(coord ob1, int 1);
friend coord operator+(int i, coord ob1);
};
coord operator+(coord ob1, int i) //right-hand built-in type
{
coord temp;
temp.x=ob1.x+i;
temp.y=ob1.y+i;
return temp;
}
coord operator+(int i, coord ob1) //left-hand built-in type
{
coord temp;
temp.x=ob1.x+i;
temp.y=ob1.y+i;
return temp;
}
Object-Oriented Programming

114

Operator Overloading 10 (Assignment Operator)


By default, when the assignment operator is applied to an object, a
bitwise copy of the object on the right is put into the object on the
left. If this is what you want, OK, no need to worry about anything.
But, as you already know, in some cases a bitwise copy is not
desirable; for example when dealing with dynamic memory.
The solution is to provide an overloaded assignment operator:
mystring &mystring::operator=(mystring &ob){
if(len<ob.len) {
//if more memory is needed
delete [] p;
p=new char [ob.len];
if(!p) exit(1);}
len=ob.len;
strcpy(p, ob.p);
return *this;
}
Object-Oriented Programming

115

Exercises
35. What is wrong with the following fragment:
class samp
{
int a;
public:
samp(int i) {a=i;}
//
};
main()
{
samp x, y(10);
//
}
35. Give two reasons why you may want to overload a classs
Constructor function?
Object-Oriented Programming

116

Exercises
37. Add two constructor functions to the following class so that
Both declarations inside main() are valid.
class samp
{
int a;
public:
// add 2 constructors here
};
main()
{
samp ob(99);
//initialize obs a to 99
samp ob_array[10];//non-initialize 10-member array
//
}
Object-Oriented Programming

117

Exercises
38. What type of operations will cause the copy constructor to be
called?
39. What is wrong with the following fragment:
void compute(int *num, int d=1);
void compute(int *num);
//
compute(&x);
40. Show how to overload the constructor for the following class so
That un-initialized objects can be created. (when creating unInitialized objects, give x and y the value 0) Use two methods.
Class myclass {
int x, y;
Public:
myclass (int I, int j) {x=I; y=j;}
}
Object-Oriented Programming

118

Exercises
41. What is wrong with the following declaration?
int f(int a=0, int b);
42. When is it appropriate to use default arguments? When is it
probably a bad idea?
43. Create a class called rational which is used to represent rational
numbers: , , etc. So your class will have two private data
members. Add the following member functions:
-a default constructor
-a parameterized constructor
-overloaded + operator
-overloaded operator
-overloaded / operator
-overloaded * operator
Object-Oriented Programming

119

Exercises
44. True or false: when a binary operator is overloaded, the left
Operand is passed implicitly to the function and the right operand
is passed as an argument?
45. Overload the == operator relative to the rational class set as
Exercise on slide 115.
46. Overload the > and < operators relative to rational class.
47. Overload the operator for the coord class.
48. Using friend functions, overload + operator relative to the
rational class so that integer values can be added to an object of
type rational (either on left or right of operand)
Object-Oriented Programming

120

Exercises
49. How do friend operator functions differ from member operator
Functions? Explain.
50. When is the assignment operator called and explain why you
might need an assignment operator?
51. Can operator=() be a friend function?
52. RE-write the class mystring (slide 69) with the following types
of operators:
- string concatenation using + operator
- string assignment using the = operator
- string comparisons using <,> and =
Object-Oriented Programming

121

Inheritance
Inheritance is one of the three principles of OO programming. In
the next few slides we will see how inheritance supports the
concept of hierarchical classification and provides support for
polymorphism.
In C++, inheritance is the mechanism with which one class can
inherit or acquire the properties of another class. It allows a
hierarchy of classes to be made, moving from the most general to
the most specific.
When one class is inherited by another class, the class that is
inherited is called the base class. The inheriting class is called the
derived class. Generally, the process of inheritance starts with
defining a base class which include all qualities/properties common
to any derived class. (Parent class/child class)
Object-Oriented Programming

122

Inheritance 2
Lets now look at a simple inheritance example:
class B {
int i;
Public:
void set_i(int x) {i=z;}
int get_i() { return i;}
};
class D : public B
//D inherits B
{
int j;
Public:
void set_j(int n) {j=n;}
int mutl() { return j * get_i();}
};
Object-Oriented Programming

123

Inheritance 3
main()
{
D ob;
ob.set_i(10);
//access base class function
ob.set_j(20);
//access derived class function
cout<<mutl()<<endl;
//display 200
return 0;
}

Note that the keyword public tells the compiler that all public
members of base class will also be public members of derived class;
but private members of base class remain private to it and cannot be
directly accessed by the derived class.
Also notice that the function mult() cannot directly access private
member i in base class B. This is to preserve encapsulation.
Object-Oriented Programming

124

Inheritance 4
The general form of one class inheriting another is
class derived-class : access base-class
{
//
}
The access specifier can be one of: public, private or protected,
which determines how elements of the base class are inherited by
the derived class:
public:

all public members of base class become


public members of derived class,
private: all public members of base class become private
members of derived class.
protected:??? See next slide
Object-Oriented Programming

125

Inheritance 5
There are times when you want a derived class to have access to
private members of the base class directly. To enable this feature,
C++ uses the access specifier protected for this purpose.
Its common to declare protected members of a class just after
declaring private members and before public members. When a
protected member is inherited as public by a derived class, it
becomes a protected member of the derived class. If the base
class is inherited as private, protected members of the base class
become private members of the derived class.
If a base class is inherited as protected, then public and protected
members of the base class become protected members of the
derived class. Of course, private members of the base class remain
private to the base class.
Object-Oriented Programming

126

Inheritance 6
Lets look at an example:
class samp{
int a;
Protected:
//still private to samp but accessible
int b;
//by derived classes
Public:
int c;
samp(int x,int y, int z) {a=x; b=y; c=z;}
int geta() {return a;}
int getb() {return b;}
};
main() {
samp ob(1,2);
ob.b=3;
//Error: b is protected and hence private
ob.c=4;
//legal
cout<<geta()<< <<getb()<< <<ob.c<<endl;
}
Object-Oriented Programming

127

Inheritance 7
When protected members are inherited as public:
class base{
Protected:
int a, b;
Public:
void setab(int n, int b) {a=n;b=m;}
};
class derived : public base{
Int c;
Public:
void setc(int x) {c=x;}
void showabc() {cout<<a<< <<b<< <<c<<endl;}
};
//direct access
main(){
derived ob;
ob.setab(1,2); ob.setc(3);
ob.showabc(); }//but a and b inaccessible outside class
Object-Oriented Programming

128

Inheritance 8
When protected members are inherited as protected:
class base{
Protected:
int a, b;
Public:
void setab(int n, int b) {a=n;b=m;}
};
class derived : protected base{ //inherit as protected
int c;
Public:
void setc(int x) {c=x;}
void showabc() {cout<<a<< <<b<< <<c<<endl;}
};
//direct access
main(){
derived ob;
ob.setc(3);
ob.setab(1,2); //Error:
why?
ob.showabc(); }
Object-Oriented Programming

129

Inheritance 9
Notice the following statements about inheritance:
- The constructors of a base/derived class are called in order of
derivation while their destructors are called in the reverse order
- If the base classs constructor expects arguments then these
arguments must be passed through the derived classs constructor.
The general form of the derived classs constructor is:
derived_class(arg-list) : base (arg-list)
{
//body
}
Its possible for both the base class and the constructor class to
take the same argument. Its also possible for the derived class
to ignore any arguments and pass them to the base class.
Object-Oriented Programming

130

Inheritance 10
In this program, base and derived classes both expect arguments:
class base{
int i;
Public:
base(int n) {cout<<Constructing base class<<endl;
i=n;}
~base() {cout<<Destructing base class<<endl;} };
class derived : public base{
int j;
Public:
derived(int n, int m) : base(m){
cout<<Constructing derived class<<endl;
j=n; }
~derived(){cout<<Destructing derived class<<endl;}
};
main() {
derived o(10,20);
//}
Object-Oriented Programming

131

Multiple Inheritance
A class can inherit more than one class in two ways:
1- A new class may be derived from an already derived class.
2- A new class may be derived from more than one base class.
In case 1, constructors are called in the order of derivation and
destructors in the reverse order. In case 2, constructors are called
In the order left to right and destructors in the opposite order.
When deriving from multiple base classes, case 2:
class derived-class : access base1,access base2,
{
//body of class }
Case 1:
Base1
Derived1
Derived2
Case 2:

Base1

Base2
Derived

Object-Oriented Programming

132

Multiple Inheritance 2
Case 1 example: (class hierarchy)
Class B1 {
int a;
Public:
B1(int x) {a=x;}
int geta() {return a;}
};
class D1 : public B1 {
int b;
Public:
D1(int x, int y) : B1(y)
int getb() {return b;}
};
class D2 : public D1 {
int c;
Object-Oriented Programming

{ b=x;}

//continued

133

Multiple Inheritance 3
Public :
D2(int x, int y, int z) : D1(y, z) {c=z;}
void show()
{ cout<<geta<< <<getb()<< <<getc()<<endl;}
};
main()
{
D2 ob(1,2,3);
ob.show();
}

The output of this program would be: 3 2 1


D1 inherits B1 as public and so B1s public members become D1s
public members and in turn D1s public members become public
members of D2 since D2 inherits D1 as public and hence the way
geta() and getb() are accessed in show() in D2; they are used
directly since they have become public members of D2.
Object-Oriented Programming

134

Multiple Inheritance 4
Case 2 example: (Multiple base class inheritance)
class B1 {
int a;
Public:
B1(int x) {a=x;}
int geta() {return a;}
};
class B2 {
int b;
Public:
b2(int x) {b=x;}
int getb() {return b;}
};
class D : public B1, public B2 {
int c;
Public:
//continued
Object-Oriented Programming

135

Multiple Inheritance 5
D(int x, int y, int z) B1(z), B2(y) { c=x;}
void show() { cout<<geta()<<getb()<<getc()<<endl;}
};
main()
{
D ob(1,2,3);
ob.show();
}

This program has the same output as the previous one: 3 2 1


when a derived class derived3 inherits from two classes derived1
and derived2 which in turn both inherit a base class Base, a
problem can arise: the Base class is inherited twice and this would
cause complications. To resolve this issue, C++ has a mechanism by
which only one copy of Base will be included in derived3: a virtual
base class. See the example on the next slide.
Object-Oriented Programming

136

Multiple Inheritance 6
class base {
Public:
int x; };
class derived1 : virtual public base {
Public:
int y;};
class derived2 : virtual public base {
Public:
int z;};
class derived3 : public derived 1, public derived2 {
Public:
int product() {return x*y*z;} };
main() {
derived3 ob;
ob.x=1;
//ok because only one copy is present
ob.y=2; ob.z=3;
cout<<Product is: <<ob.product<<endl; }
Object-Oriented Programming

137

Exercises
53. Examine this skeleton:
class mybase{
int a, b;
Public:
int c;
void setab(int I, int j) { a=I; b=j;}
void getab(int &I, int &b) { i=a; j=b;}
class derived1 : public mybase {//.};
class derived2 : private mybase { //};
main(){
derived o1;
derived2 o2;
int I, j;
//.
}
Within main(), which of the following are legal:
a) o1.getab(i, j);
Object-Oriented Programming

};

b) o2.getab(i, j); c) o1.c=10;

d) o2.c=10

138

Exercises
54. What happens when a protected member is inherited as:
i) Public?
ii) Protected?
iii) Private?
55. Explain why the protected category is needed.
56. What is the output of the following program:
class base{
Public:
base() { cout<<Constructing base<<endl;}
~base() { cout<<Destructing base<<endl;}
};
class derived : public base {
Public:
derived() { cout<<Constructing derived<<endl;}
~derived() { cout<<Destructing derived<<endl;}
};
maib(){
derived o; }
Object-Oriented Programming

139

Exercises
57. What is the output of the following program:
class A {
Public:
A() { cout<<Constructing A<<endl;}
~A() {cout<<Destructing A<<endl;} };
class B {
Public:
B() { cout<<Constructing B<<endl;}
~B() { cout<<Destructing B<<endl;} };
class c : public A, public B{
Public:
C() { cout<<Constructing C<<endl;}
~C() { cout<<Destructing C<<endl;} };
main()
{
C ob;
}
Object-Oriented Programming

140

Exercises
58. Write a constructor for C so that it initializes k and passes on
arguments to A() and B():
class A {
int i;
Public:
A(int a) { i=a;}
};
class B {
int j;
Public:
B(int b) { j=b;}
};
class C {
int k;
Public:
//constructor for C
};
Object-Oriented Programming

141

Exercises
59. Create a base class called building that stores the number of
floors a building has, the number of rooms and its total square area.
Create a derived class called house that inherits building and also
stores: the number of bedrooms and bathrooms. Then create
another derived class called office that inherits building and
that stores: the number of telephones and number of desks. Test it.
59. Explain what protected means when
- referring to members of a class and
-used as an inheritance access specifier.
59. Most operators overloaded in a base class are available in a
base class for use in a derived class. Most but not all. Think of an
operator that may not be inherited. Give the reason why it may
not be inherited by derived classes.
Object-Oriented Programming

142

Exercises
62. What is the output of the following program? (inserters)
Class coord {
int x, y;
Public:
coord() { x=0; y=0;}
coord(int i, int j) { x=i; y=j;}
friend ostream &operator<<(ostream &stream, coord ob);
};
ostream &operator<<(ostream &stream, coord ob)
{
stream<<ob.x<<, <<ob.y<<endl;
return stream;
}
main()
{
coord a(1, 1), b(10, 20);
cout<<a<<b;
}
Object-Oriented Programming

143

Exercises
63. What is the output of the following program:
class book {
string title;
string author;
int ID;
Public:
book(string t, string a, int n)
{ title=t; author=a; ID=n; }
friend ostream &operator<<(ostream &stream, book &ob);
friend istream &operator>>(istream &stream, book &ob);
};
friend ostream &operator<<(ostream &stream, book &ob)
{
stream<<ob.title<< <<ob.author<< <<ID<<endl;
}
//see next slide
Object-Oriented Programming

144

Exercises
friend istream &operator>>(istream &stream, book &ob)
{
cout<<Book title: ; stream>>ob.title;
cout<<Book author: ; stream>>ob.author;
cout<<Book ID: ;
stream>>ob.ID;
return stream;
}
main()
{
book ob(OO Programming in C++, W Savitch, 1234);
cout<<ob;
cin>>ob;
cout<<ob;
}

This is a typical use of overloaded inseters and extracters and you


may find them useful for your group project work. As you can see
they can make writing complex programs easier.
Object-Oriented Programming

145

Exercises
64. What is the output of the following program: (this program
demonstrates some more file I/O functions)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main()
{
string s(Hello), s2;
fstream file(text.txt", ios::in|ios::out);
file<<s;
file.seekp(0);
//set file pointer to start
file>>s2;
//of stream
cout<<s2<<file.tellp()<<endl; //current position of
file.close();
//file pointer
}
Object-Oriented Programming

146

Exercises
65. What is the output of the following program:
#include <fstream>
#include <string>
using namespace std;
main()
{ char ch;
ifstream file(text.txt);
ch=file.peek();
if(isupper(ch)) cout<<Is upper<<endl;
file.get(ch); //still gets first character
cout<<ch<<endl;
file.putback(ch);
file.get(ch);
cout<<ch<<endl;
}
Object-Oriented Programming

147

Exercises
66. Which program is better? Explain why (Hint: Encapsulation)
class X {
public:
X() {x=0;}
int x;
};
main()
{
X ob;
b.x=7;
}

Object-Oriented Programming

class Y {
int x;
public:
Y() { x=0;}
void set(int k) {x=k;}
};
main()
{
Y ob;
ob.set(7);
}

148

Polymorphism (Virtual Function)


Polymorphism means one interface, multiple methods; C++ supports
polymorphism in two ways: first, using overloaded functions and
operators (also called static binding) and second, using virtual
functions which is achieved at run time (also called late binding or
dynamic binding)
A pointer declared as a pointer to a base class can also be used to
point to any class derived from that base class: (reverse is not true)
base *p;
base base_ob;
derived derived_ob;
p=&base_ob;
//ok, natural
p=&dderived_ob;
//also ok

But with pointer p now, we can only access the inherited members;
we cannot access members specific to the derived object.
Object-Oriented Programming

149

Polymorphism (Virtual Function) 2


Lets examine this example:
class base {
int x;
public:
void setx(int a){x=a;}
int getx() {return x;}
};
class derived : public base{
int y;
public:
void sety(int b) {y=b;}
int gety() {return y;}
};
main() {
base *p; base b_ob; derived d_ob;
p=&b_ob; p->setx(11);
cout<<Base object x: <<p->getx()<<endl;
Object-Oriented Programming

//---->

150

Polymorphism (Virtual Function) 3


p=&d_ob; p->setx(55); //use p to access derived op
//cannot use p to set y, so do it indirectly
d_ob.sety(77);
cout<<Derived object x: <<p->getx()<<endl;
cout<<Derived object y: <<d_ob.gety()<<endl;
return 0;
}
You may say: so what?. Pointers to base classes are very
important in understanding how virtual functions and late binding
work.
Polymorphism using virtual functions is the last important feature
of OO programming. You may not see the point of virtual functions
at first, so be patient and after some theory and examples you will
slowly understand their place.
Object-Oriented Programming

151

Polymorphism (Virtual Function) 4


A virtual function is a class member function that is declared inside
a base class and redefined by a derived class. Just precede the
functions declaration with the keyword virtual. The keyword
virtual is not needed when a virtual function is redefined in a
derived class.
When a base class containing a virtual class is inherited, the derived
class redefines the virtual function relative to the derived class.
This mechanism implements the one interface, multiple methods
philosophy.
The virtual function inside the base class, defines the form of the
interface to that function. Each redefinition of the virtual function
by a derived class implements its operation as it relates specifically
to the derived class.
Object-Oriented Programming

152

Polymorphism (Virtual Function) 5


Now lets see what happens when a virtual function is called using
a pointer. Remember that a base class pointer can be used to point
to a derived class object.
When a base class pointer points to a derived class object that
contains a virtual function and that virtual function is called through
that pointer, the compiler decides which version of that function
to call based on the type of object being pointed to by that pointer,
and this decision is made at runtime. A simple example:
class base {
public:
virtual void func()
{
cout<<Using base version of func();
}
};
//----->
Object-Oriented Programming

153

Polymorphism (Virtual Function) 6


class derived1 : public base {
public:
void func() {
cout<<using derived1 version of func();
}
};
class derived2 : public base {
public:
void func() {
cout<<Using derived2 version of func();
}
};
main()
{ base *p; base ob;
derived1 d1_ob; derived d2_ob;
p=&ob;
p->func();
Object-Oriented Programming

//----->

154

Polymorphism (Virtual Function) 7


p=&d1_ob;
p->func();
p=&d2_ob;
p->func();
}
Note that redefining a virtual function in a derived class is not the
same as function overloading. There is a special term used for
referring to redefined virtual functions: overridden. Can you think
of the differences between overridden and overloaded functions?
The important point to know is this: it is the type of object being
pointed to by a base class pointer that determines which version
of an overridden virtual function will be executed, and this decision
is made at runtime.
Object-Oriented Programming

155

Polymorphism (Virtual Function) 8


One of the main applications and uses of runtime polymorphism and
virtual functions is in graphical event-driven programming, where
your program must respond to different events at random.
Consider the event of a mouse-click on a menu item, on a windows
title bar, on a windows status bar, on a text-box, on a. Your
program must have a function that responds to these events and
its only natural to have the same function (one interface) to
respond to all these different but similar events; the type of the
object being clicked (pointed to) determines which version of the
function to be called. Is it a text-box thats being clicked, is it a
window title bar, is it a button, is it a menu item. Also note that
these events happen at runtime. The programmer wouldnt know
which version of the function will be called. This is determined at
runtime.
Object-Oriented Programming

156

Polymorphism (Virtual Function) 9


A pure virtual function is a function which has no definition and
must be redefined by any derived class. A class that contains at
least one pure virtual function is called an abstract class.
class area {
public:
double dim1, dim2;
void setarea(double d1, double d2) { dim1=d1; dim2=d2;}
double getArea() =0;
};
class rectangle : public area{
Public:
double getArea() { return dim1 * dim2;}
};
class triangle : public area {
public:
double getArea() { return dim1 * dim2 * 0.5;}
};
----->
Object-Oriented Programming

157

Polymorphism (Virtual Function) 10


main()
{
area *p;
rectangle r;
triangle t;
r.setarea(3.3, 4.5);
t.setarea(4.0, 5.0);
p=&r;
cout<<Rectangle area: <<p->getarea()<<endl;
p=&t;
cout<<Triangle area: <<p->getarea()<<endl;
}

But an abstract class is an incomplete type and hence you cannot


declare objects of the type. But you can still declare a pointer to
an abstract class as in this example. The function getarea() is
pure which insures that each derived class will override it.
Object-Oriented Programming

158

Polymorphism (Virtual Function) 11

Dynamic binding can improve reuse by letting old code call new code.
Before OO came along, reuse was accomplished by having new code
call old code. For example, a programmer might write some code that
called some reusable code such as printf().
With OO, reuse can also be accomplished by having old code call new
code. For example, a programmer might write some code that is called
by a framework that was written by their great, great grandfather.
There's no need to change great-great-grandpa's code. In fact, it
doesn't even need to be recompiled. Even if all you have left is the
object file and the source code that great-great-grandpa wrote was
lost 25 years ago, that ancient object file will call the new extension
without anything falling apart. That is extensibility, and that is OO.
Object-Oriented Programming

159

C++FAQ on soft-eng.local

Note: The following is taken from the C++ FAQ:

Virtual Function (Type Compatibility)


As you know, C++ is a strongly typed language which implies that
You cannot always mix variables/objects of different types.
Suppose we have the following two classes:
class person {
Public:
virtual void print() {cout<<N: <<name<<endl;}
string name;
};
class student : public person{
Public:
void print() {cout<<N:<<name<<Y:<<year<<endl;}
int year;
};
person p;
student s;
Object-Oriented Programming

160

Virtual Function (Type Compatibility) 2


Now, anything that is a student is also a person and the following
should be legal:
s.name=X;
s.year=2;
p=s;
C++ allows this but the reverse is not possible. Although this sort
of assignment is ok, the value of the member variable year is lost
(the slicing problem):
cout<<p.year;
//will generate an error
This is unacceptable: you may sometimes want to treat a student as
a person without losing the name property. To do this you can use
pointers to dynamic objects:
person *p;
student *s;
s=new person; s->name=X;
s->year=2;
p=s;
Now the statement p->print(); will print the following: N: X Y: 2
Why: Because the function print() is virtual.
Object-Oriented Programming

161

Exercises
(For question 67---73, suppose an inheritance hierarchy with a base class Base and a
derived class Derived. True or False)

67. For Derived to override an inherited member function, Base


must declare the function to be virtual.
68. If a function is declared as virtual in Base, then it is
automatically virtual in Derived.
69. If a function is not declared in Base, then it may be declared as
virtual in Derived.

A pure virtual function must have a return type of void.

If Base is an abstract class, then all member functions of Base


Must be pure virtual functions.
Object-Oriented Programming

162

Exercises
72. Virtual functions are the only C++ mechanism required to achieve
runtime polymorphism.
73. If a function is declared virtual in Base, then Derived must
Override it.

(For questions 74---89, assume the following class declarations and main()function.
Assume that implementations are supplied for each class)
class Base {
class D : public Base{
public:
public:
void F();
virtual void F();
virtual void G()=0;
void G();
virtual void H();
void H();
virtual void I();
virtual void J();
};
};
class E : public D {
Public:
void F();
void G(); };
Object-Oriented Programming

163

Exercises
main()
{
D* pD=new D;
Base* pB=pD;
E* pE=new E;
pB->F();
pB->G();
pB->H();
pB->I();

//line
//line
//line
//line

1
2
3
4

pD->F();
pD->G();
pD->I();
pD->J();

//line
//line
//line
//line

5
6
7
8

//see next slide


Object-Oriented Programming

164

Exercises
pB=pE;
pD=pE;

pB->F();
pB->G();
pB->H();
pB->I();

//line
//line
//line
//line

9
10
11
12

pD->F();
pD->J();

//line 13
..line 14

pE->F();
pE->H();

//line 15
//line 16

Line 1:
1) Base::F()

Object-Oriented Programming

2) D::F()

3) E::F()

4) None

165

Exercises
75. Line 2:
1) Base::G()
2) D::G()
3) E::G()

4) Base::H()
5) D::H()
6) 1 and then 4

7) 2 and then 4
8) 2 and then 5
9) None

76. Line 3:
1) Base::H()

2) D::H()

3) E::H()

4) None

77. Line 4:
1) Base::I()

2) D::I()

3) E::I()

4) None

2) D::F()

3) E::F()

5) None

2) D::I()

3) E::I()

4) None

Line 5:
Base::F()

Line 7:

1) Base::I()
Object-Oriented Programming

166

Exercises
80. Line 6:
1) Base::G()
2) D::G()
3) E::G()

4) Base::H()
5) D::H()
6) 1 and then 4

81. Line 8:
1) Base::J()

2) D::J()

3) E::J()

4) None

82. Line 9:
1) Base::F()

2) D::F()

3) E::F()

4) None

83. Line 10:

Base::G()

D::G()

E::G()

Line 11:
1) Base::H()
Object-Oriented Programming

4) Base::H()
5) D::H()
6) 2 and then 4
2) D::H()

7) 2 and then 4
8) 2 and then 5
9) None

7) 2 and then 5
8) 3 and then 5
9) None

3) E::H()

4) None

167

Exercises
85. Line 12:
1) Base::I()

2) D::I()

3) E::I()

4) None

2) D::F()

3) E::F()

4) None

2) D::J()

3) E::J()

4) None

2) D::F()

3) E::F()

4) None

2) D::H()

3) E::H()

4) None

86. Line 13:


1) Base::F()

87. Line 14:


1) Base::J()

88. Line 15:


1) Base::F()

85. Line 16:


1) Base::H()

Object-Oriented Programming

168

Exercises
90. Based on the class definitions given on slide 160, what is the
output of the following main function:
main()
{
person *p;
student *s;
s=new student;
s->name="XXX"; s->year=2;
p=s;
p->print();
s->print();
}
91. What would be the output had there not been the keyword
virtual?
92. What is the problem with the assignment of a derived class
object to a base class object?
Object-Oriented Programming

169

Templates
Using templates, you can define functions and classes which have
parameters for their type names. This will allow you to write
generic functions and classes. Here is an example of a template
function:
Template<class T>
//T is parameter for type
void swap(T& var1, T& var2)
{
T temp=var1;
var1=var2;
var2=temp;
}
main()
{ int x=1, y=2;
swap(x, y);
cout<<x << <<y<<endl;
char char1=a, char2=b;
swap(char1, char2); cout<<char1<< <<char2<<endl;
}
Object-Oriented Programming

170

Templates 2
The output of the program is:
2
b

1
a

The compiler creates a definition for each type that you use in the
program. It will not however create a definition of each possible
Type that you may use in the program. Definitions will be created
Only for the types that are used in the program. In this example,
definitions only for int and char would be created.
Note that the base type can be anything: C++ built-in types and
user-defined structs and classes.
The idea of function templates is that some algorithms are generic
in nature, that is they apply regardless of the data type used. The
swap function is one such example. Another example is a function to
find the maximum of two values or a sorting function.
Object-Oriented Programming

171

Templates 3
You can also define template or generic classes for example a
template list class that can hold a list of items of any type. First
Lets consider a simple illustration example:
template <class T>
class pair
{
T first;
T second;
public:
pair();
pair(T first_value, T second_value);
void set_element(int position, T value);
T get_element(int position);
};
Object-Oriented Programming

172

Templates 4
template<class T>
void pair<t>::set_element(int position, T value) {
if (position ==1)
first=value;
else if (position==2)
second value;
else exit(1);
}
template<class T>
T pair<T>::get_element(int position) {
if(position==1)
return first;
return second;
}
template<class T>
pair<T>::pair(T first_value, T second_value) {
first=first_value; second=second_value;
}
//
--->
Object-Oriented Programming

173

Templates 5
main()
{
pair<int> score;
pair<char> seats;
score.set_element(1, 0);
score.set_element(2, 4);
//
}
The class name before the scope resolution operator is pair<T>,
not just pair. Also notice that both the template class definition and
the template member functions are preceded by template<class T>
This example was for demonstration only; lets now look at a more
practical example involving a template class definition.
Object-Oriented Programming

174

Template 6
In this example, we will define a template class whose objects are
lists. The lists can be lists of any type: a list of ints, a list of chars,
A list of strings, a list of structs, a list of any user-defined class
First, the interface file or the header file:
#ifndef LIST_H
#define LIST_H
#include <iostream.h>
template <class T>
class list {
T *item;
int max_length;
int current_length;
public:
list(int max);
~list();
int length();
Object-Oriented Programming

// --->

175

Templates 7
void add(T new_item);
bool full();
friend ostream& operator <<(ostream& outs, const list<T>&
the list);
};
#endif
And here is a main program to test out new generic class:
main(){
list<int> first_list(2);
first_list.add(1);
first_list.add(2);
cout<<first_list = <<first_list;
list<char> second_list(5);
second_list.add(d); second_list.add(e);
second_list.add(f);
cout<<second_list = <<second_list;
}
Object-Oriented Programming

176

Templates 8
Finally, here is the implementation file:
template <class T>
list<T>::list(int max) {
max_length=max;
current_length=0;
item=new T[max];
if (item==NULL) exit(1);
}
template <class T>
list<T>::~list() {
delete [] item;
}
template<class T>
int list<T>::length() {
return current_length;
}
Object-Oriented Programming

// --->

177

Templates 9
template <class T>
void list<T>::add(T new_item) {
if(full())
exit(1);
else
{
item[current_length]=new_item;
current_length=current_length+1;
}
}
template <class T>
bool list<T>::full() {
return (current_length==max_length);
}
// --->
Object-Oriented Programming

178

Templates 10
template <class T>
ostream& operator <<(ostream& out, const list<T>& the_list)

{
for(int i=0; i<the_list.current_length;
out<<the_list.item[i];<<endl;
return out;
}
As you saw, the only difference between template classes and
ordinary classes is that in template classes, you have a parameter
type (called the base type) and not a specific type.
In this example, an array was used to represent a list. But arrays
are not ideal in situations where you dont know in advance how many
items they will store. Linked lists, as you know, solve this problem
Object-Oriented Programming

179

Templates 11
Template classes, like template functions are useful when they
contain logic which is general as you saw in the previous example.
Here is another example in which a generic stack class is created
which can be a stack of any type of objects:
#define SIZE 10

//define a constant

Template <class T> class stack {


T stack1[size];
int tos;
//index of top of stack
Public:
stack() { tos=0;}
void push(T obj);
T pop();
};
Object-Oriented Programming

180

Templates 12
Template <class T> void stack<T>::push(T obj){
if(tos==SIZE){
cout<<Stack is full;
return;
}
stack1[tos]=obj;
tos++;
}
Template <class T> T stack<T>::pop(){
if (tos==0) {
cout<<stack is empty;
return 0;
}
tos--;
return stack[tos];
}
Object-Oriented Programming

181

Templates 13
main(){
stack<char> s1;
s1.push(x); s1.push(y);
s1.push(z);
for(int i=0; i<2; i++)
cout<<Pop s1: <<s1.pop()<<endl;
stack<double> s2;
s2.push(1.2);
s2.push(2.4);
s2.push(4.8);
for(int i=0; i<2; i++)
cout<<Pop s2: <<s2.pop()<<endl;

stack<int> s3;
s3.push(2);
s3.push(4);
s3.push(8);
for(int i=0; i<2; i++)
cout<<Pop s3: <<s3.pop()<<endl;
}
Object-Oriented Programming

182

Exercises
93. Remember the selection sort algorithm from the first year?
There you used three functions: a function to swap two integers,
a function to find the index of the next smallest number in the
array and the main algorithm function which used these two
functions to sort the array. Convert these functions to generic
functions so that they can be used to sort arrays of any type (ints,
chars, strings)
94. On the last few slides an array was used to represent a list of
items; arrays however are limiting. Now, implement the class
using linked lists instead. Add the following functions to the class:
- a function to remove the top element of the generic linked list
- a function to search for an item in the list
- a function to test if the list is empty
Object-Oriented Programming

183

Static Class Members


Class member variables can be declared as static which means that
only one copy of that variable exits, no matter how many objects
Of that class are created. This static member variable is shared
Between all the objects of that class. Also, that variable can be
Used by any class derived form that base class.
It is possible to access a class static member variable even before
An object of that class is created. Its like a global variable whose
Is scope is restricted to the class in which it is declared.
But when you declare a static data member, you are not defining it.
You must provide a definition for it outside the class. Also note,
that all static numerical data members are initialized to zero by
default. You can of course initialize a static data member to any
Value you want.
Object-Oriented Programming

184

Static Class Members 2


The principal reason static data members are used is to prevent the
need for global variables. As you know, classes that rely on global
Variables break the encapsulation rule, which is very fundamental to
OO programming.
class myclass {
static int i;
public:
void set(int n) {i=n;}
int get() {return i;}
};
int myclass::i;
main() {
myclass::i=12;
//no object is referenced
myclass o1, o2;
//o1.set(12);
//access through function
cout<<o1.i : <<o1.get()<<\n;
//print 11
cout<<o2.i :<<o2.get()<<\n;
//print 11
}
Object-Oriented Programming

185

Static Class Members 3


One interesting use of static data members is when you want to
Coordinate access to some resource (file, array, variable, printer,
connection) between several objects.
Another use is when you want to keep track of the number of
Objects that are in existence at any time. Lets look at an example
Which demonstrates this:
class test {
static int count;
publci:
test() { count++;}
~test() { count--;}
int getCount() {return count;};
};
Object-Oriented Programming

186

Static Class Members 4


main() {
test o1, o2, o3;
cout<<o1.getcount()<<endl;
test *p; p=new test;
cout<<o1.getCount();
delete p;
cout<<o1.getcount();
}
The first output statement will output: 3
The second one will output: 4
The last one will output: 3
You can also have static member functions but they are uncommon
And not of much use.
Object-Oriented Programming

187

Namespaces
Scope is the section of the program where a name has a meaning.
The more localised variables are the better. There's

file scope - entities can be made visible only to entities in the


same file.

function scope - entities can be made visible only to the


function they're created in.

block scope - delimited by ' {' and ' }'.

class scope - entities can be made visible only to the class


they're created in.

namespaces - A namespace is like a class that has no


functionality. Only used for creating a new name space.
You can put an entity into a namespace by doing something like:
namespace test {
int i;
}
Object-Oriented Programming

188

Namespaces 2
then using test::i to access the variable. The command
using namespace test
will make all the entities in the namespace available for the rest of
the unit that the statement is in, without the test:: being
necessary. The standard library names are in the std namespace.
It's tempting to put using namespace std at the top of each file
to access all the standard routines, but this pollutes the global
namespace with many routine names you'll never use, so consider
using more specific commands like
using std:string
It's possible for a local variable to mask a global variable of the
same name. If in a function that has a local variable i you want to
access a global variable i, you can use ::i, but it's better to avoid
such name clashes in the first place.
Object-Oriented Programming

189

Namespaces 3
The main reason for using namespaces is this: in large programming
Projects, the possibility of name clashes increases. Different
Programmers may use similar identifiers for their part of the
project and this will cause name clashes. To alleviate this problem,
C++ supports namespaces b y which you can decrease the probability
Of name clashes with other programmers.
Looking back at the namespace we created (test) we can access its
Members in three ways:
1) by specifying the name using the scope resolution operator
2) with a using directive to introduce all names in the namespace
or with a using declaration to introduce names one at a time
We saw method 1 in the previous slides. Using method 2, we can
Object-Oriented Programming

190

Namespaces 4
Use the using directive: using namespace test;
This will make all the test namespace names available for use and
you dont have to use the tedious namespace name plus scope
resolution operator for each name used in your program.
The third way is by using the using declaration:
using std::string;

This way you include only some part of a name space. There is a
special C++ namespace called std that includes the definitions for
all the new features of the language. But it is advised not to use the std
namespace except in small programs, because this would pollute the global
namespace. In particular, do not use the using standard std or other
namespaces in header files because header files may be included in
Several files and this would pollute all those files and programs. Old C
libraries must be prefixed by c, for example #include <cstring>
Object-Oriented Programming

191

Standard Template Library (STL)


After studying this topic, you may ask: why did we not start C++
With this topic? The reason you may ask this question is that
STL makes C++ programming so much easier and productive. But
You would not have appreciated its power until you did some
Basic programming and gradually introduced to STL.
C++ templates are the basis of STL. STL is about generic
Programming. It has many many classes, methods, and functions
Which you can easily use in your programs.
We will not cover All the details of the package, instead we will
concentrate on the
1) Ideas and concepts of the package
2) Look at the main features of the package
Look at some examples.
Object-Oriented Programming

192

STL 2
Before delve into the details of STL, consider the following diagram:
i

k
sort, search, swap

int, char, double

Array, list, queue

A sort algorithm for integers, one for chars, one for strings
A sort for arrays (array of integers, chars, one for lists.
A search algorithm for lists(list of integers, strings),
In this scenario, you would need i*j*k versions of code. If you use
Object-Oriented Programming

193

STL 3
Template functions, the i-axis can be dropped and only j*k versions
Of code would be needed. Next, if you make your algorithms work
On arrays and lists and , only j+k versions of code would be needed.
STL accomplishes this and thus simplifies the software development
Process. STL consists of five main components:
1) Algorithms: computational procedure that is able to work on
different containers
2) Container: object that can hold collection of other objects
3) Iterator: abstraction of access to containers so that an
algorithm can work on different containers
4) Function Object: a class that has the function call operator
(operator ()) defined
5) Adapter: encapsulates a component to provide another interface
Object-Oriented Programming

194

STL 4
An example is in place:
#include <iostream>
#include <vector>
using namespace std;
main()
{
vector<int> v;
//declare an array container
v.push_back (3);
//append 3 to the array
v.push_back (7);
v.push_back (2);
vector<int>::iterator first=v.begin (); //iterator
vector<int>::iterator last=v.end ();
//iterator
while(first !=last)
cout<<*first++<<" ";
}
Object-Oriented Programming

195

STL 5
Another example involving containers, iterators and algorithms:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
main()
{
vector<char> v(3,a);
//declare an array container
v.push_back (a);
//append 3 to the array
v.push_back (f);
v.push_back (c);
vector<char>::iterator first=v.begin (); //iterator
vector<char>::iterator last=v.end ();
//iterator
soft(first,last);
//sort the array
while(first !=last)
cout<<*first++<<" ";
}
Object-Oriented Programming

196

STL 6
Yet another example:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
main()
{
vector<float> v(4,1.5);
for(int k=0; k<4, k++)
cout<<v[k]<< ;
vector<float> new1_v(v);
vector<float> new2_v=v;
vector<float> new3_v(v.begin(),v.end());
(new1_v==new2_v) && (new2_v==new3_v) ? cout<<Equal : \
cout<<Different;
cout<<v.capacity()<<endl;
}
Object-Oriented Programming

197

STL 7
Yet one more example:
#include <iostream> #include <vector> #include <algorithm>
main()
{ vector<double> a;
a.empty() ? cout<<Empty : cout<<Not empty; //empty
vector<string> v(2,string);
vector<string> w(2, word);
v.swap(w);
//swap v and w
cout<<v[0]<<endl;
//word
vector<int> z(3,5);
z.push-back(8);
cout<<z.front()<< <<z.back()<<endl; //5 8
cout<<z.size()<<endl;
//4
z.pop-back()<<endl;
//5 5 5
cout<<z.size()<<endl; //3
cout<<z.back()<<endl;
//5
}
Object-Oriented Programming

198

STL 8
And another example: (the insert & erase functions)
#include <iostream> #include <vector>
main(){
vector<int> v;
//vesrion 1 of insert
v.insert(v.begin(),6);//first argument is an iterator
cout<<v.capacity()<<endl;
cout<<v[0]<<endl;
vector<int> w;
w.insert(w.begin(), 2, 9);
//9 9
vector<int> x(1,3);
x.insert(x.end(), v.begin(),v.end()); // 3 9 9
vector<float> z(4, 7.5);
//7.5 7.5 7.5 7.5
z.insert(z.begin (),44);
//44 7.5 7.5 7.5
z.insert(z.end (),66);
//44 7.5 7.5 7.5 66
z.erase(z.begin());
//7.5 7.5 7.5 66
z.erase(z.begin(),z.end());
//same as v.clear()
}
Object-Oriented Programming

199

STL 9
More algorithms and functions: (header files are left out for space)
int main(){
vector<int> coll;
vector<int>::iterator pos;
coll.push_back(2);
coll.push_back(5);
coll.push_back(4);
coll.push_back(1);
coll.push_back(6);
coll.push_back(3);
pos = min_element (coll.begin(), coll.end());
cout << "min: " << *pos << endl;
pos = max_element (coll.begin(), coll.end());
cout << "max: " << *pos << endl;
sort (coll.begin(), coll.end());
pos = find (coll.begin(), coll.end(),3);
reverse (pos, coll.end());
//reverse from 3 onwards
for (pos=coll.begin(); pos!=coll.end(); ++pos)
cout << *pos << ' ';
}
Object-Oriented Programming

200

STL 10
STL has two main types of containers:
1- sequence containers (elements organised in linear fashion)
- vector (generalization of array; resizable; contiguous)
- list (lfor long sequences; insert/delete from the middle)
- deque (double ended queue; pushed at back, poped from front)
2- Associative containers (associate keys with values)
- set (math. Set, membership, adding, subset, equal operations)
- multiset (bag, set where multiple occurrences allowed)
- map (pairs, keys plus values)
- multimap (map with multiple keys)
We will not consider them all of course, but once you learn about one
or two container types, you can easily learn the others. You are no
longer new-comers and you should go out and explore for yourself if
you need to know about other functions.
Object-Oriented Programming

201

STL 11
Consider the following code fragment:
vector<int> v(5,1);
v.push_back(5);
v.insert(v.begin()+2, 7);

1
1

1
1

1
1

1
1
?

//1

1
1

//1
//2
//3

//2
//3

Can you say what will the vector v will look like after line 3? Insert
in the middle is expensive. So is removing from the middle, because
elements would have to be relocated in memory.
Object-Oriented Programming

202

STL 12
A vector stores its elements contiguously in memory. Because of
that it is easy to access an element directly by its position, using
the subscripting operator []. That also allows vector's iterators to
be random access iterators.
However, the way vector stores its elements also makes it hard to
insert and remove them. Because it has to keep everything in one
single chunk of memory, outgrowing it means allocating a bigger
chunk and copying all elements to this new place, and this may be
very slow. When you insert or remove an element in the middle of a
vector, all subsequent elements have to change position. This is
expensive and makes all iterators that reference those relocated
elements invalid.
Inserting/removing at the end of vectors is cheap and quick.
Object-Oriented Programming

203

STL 13
A list keeps its elements in memory by dynamically allocating a
chunk of memory for each inserted element. Those chunks won't
necessarily be contiguous in memory and therefore it is not possible
to find them directly. Each of those chunks, known as nodes, points
to the next and previous nodes, and all we have initially is the
address of the first and last ones. The way of finding the other
ones is by following the links from the first or last one.
Although locating elements in a list is hard, it is very easy to insert
and remove elements from it, either at the begining, end, or any
position if you have an iterator pointing to that position in advance.
Moreover, no previously defined iterators get invalidated by
insertions and removals, because no element has to change memory
positions because of that. The nature of your program will dictate
whether to use a vector or a list.
Object-Oriented Programming

204

STL 14
A list container example:
main(){
list<int> l;
l.push_front(1);
l.push_front (2);
l.push_front(3);
cout<<*l.begin ()<<endl<<cout<<*--l.end ()<<endl;
list<int>::iterator first=l.begin(),second=++l.begin();

list<int>::iterator last=l.end ();


cout<<*second<<endl;
//see last line
for(int i=0; i<2; i++) first++;
l.insert (first,18);
first=l.begin ();
while(first!=last){
cout<<*first<<" ";
first++;
}
cout<<l.size(); //4
cout<<*second<<endl;
//points to same location
}
Object-Oriented Programming

205

STL 15
Another list container example:
int main(){
list<int> l1, l2;
l1.push_front(1);
//1
l1.push_back(2); //2 1
l1.push_front(3);
//2 1 3
l1.push_front(2);
//2 1 3 2
l1.sort();
// 3 2 2 1
list<int>::iterator first=l1.begin ();
list<int>::iterator last=l1.end ();
while(last!=first){
--last;
cout<<*last<<" "; }
l2.assign(l1.begin(), l1.end());
// assign l1 to l2
l1.swap(l2);
//swap the contents of l1 and l2
l2.remove(3); //delete 3 (and duplicates if any)
}
Object-Oriented Programming

206

STL 16
One more example:
main(){
list<int> l,l2;
l.push_front(1);
l.push_front (2);
l.push_front(3);
list<int>::iterator nums_iter,itr;
nums_iter = find (l.begin(),l.end(), 2); //algortithm
if (nums_iter != l.end())
nums_iter = l.insert (nums_iter, -22);
l2.assign(l.begin(), l.end());
while(l.size ()>0) {
cout<<l.front ()<<" ";
l.pop_front ();
}
l2.sort ();
//???
l2.reverse();
//???
l2.remove(3);
//??? (removes duplicates too)
}
Object-Oriented Programming

207

STL 17
An iterator is an object that encapsulates the state and behaviour
necessary to iterate over a container. It behaves differently for
each container, but the interface masks the differences and makes
it look the same. An iterator performs three simple operations
- increment (operator++) move the iterator forward to the
next object
- dereference (operator*) fetch the current object the
iterator points to
- comparision(operator==) compare the iterator with
iterators marking the beginning and end of the container
container
begin()
Object-Oriented Programming

++iterator

*iterator

end()

208

STL 18
If you intend to use the STL containers with your own class objects,
you will need to design your classes so that they should include:
- the no-argument constructor
- copy constructor
- assignment operator
- destructor
And if you need use algorithms like sort() and find() you should also
define the following operators:
- equality operator
- inequality operator
- less than operator
- greater than operator
- less than or equal to operator
- greater than or equal to operator
Object-Oriented Programming

209

STL 19
Study the following program and guess what the output would be.
int main()
{
list<int> L,L2;
L.push_back(0);
L.push_front(1);
L.insert(++L.begin(), 2);
copy(L.begin(), L.end(), L2.begin());
L.reverse ();
cout<<*L.begin ()<<endl;
//?
// L2 contains: ? ? ?
return 0;
}

Object-Oriented Programming

210

STL 20
Consdier the following program. Can you guess the output?
int square(int i) { return i * i; }
main()
{
vector<int> V;
V.push_back(0);
V.push_back(1);
V.push_back(2);
transform(V.begin(),V.end(), V.begin(), square);
copy(V.begin(),V.end(), \
ostream_iterator<int>(cout, " "));
};
The user-defined function is applied to all elements of the container.
You can use the transform algorithm on other containers too.
Object-Oriented Programming

211

STL 21
Now lets look at how STL sets work. An STL set is a mathematical
Set which cannot have multiple values. In STL, set members are
Sorted as you insert members into the set:
#include <set>
#include <iostream>
using namespace std;
main()
{
set<int> intset;
for(int i = 0; i < 25; i++)
for(int j = 0; j < 10; j++)
intset.insert(j);
copy(intset.begin(), intset.end(), \
ostream_iterator<int>(cout, "\n"));
} //whats the output???
Object-Oriented Programming

212

STL 22
Another set example:
main()
{
typedef std::set<int> IntSet;
IntSet coll;
coll.insert(3);
coll.insert(1);
coll.insert(5);
coll.insert(4);
coll.insert(1);
coll.insert(6);
coll.insert(2);
IntSet::const_iterator pos;
for (pos = coll.begin(); pos != coll.end(); \
++pos) {
cout << *pos << ' ';
}
}
Object-Oriented Programming

213

STL 23
An example involving set membership:
main()
{
set<int> myset;
for(int j = 0; j < 10; j++)
myset.insert(j);

cout<<myset.size()<<endl;
cout<<myset.count(10)<<endl;
cout<<myset.count(2)<<endl;
copy (myset.begin(), myset.end(),
\
ostream_iterator<int>(cout," "));
}
What do you think is the output of this little program?
The member function count can be used for checking membership.
If it returns 0, it implies the element is in the list.
Object-Oriented Programming

214

STL 25
Yet another set example. In this example we use more set
functions:
main() {
set<int> intset,intset2,intset3;
for(int j = 0; j < 10; j++)
intset.insert(j);
copy(intset.begin(), intset.end(),\
ostream_iterator<int>(cout, "\n"));
for(int k = 10; k < 20; k++)
intset2.insert(k);
copy(intset2.begin(), intset2.end(),\
ostream_iterator<int>(cout, "\n"));
set_intersection(intset.begin (),intset.end(), \
intset2.begin (),intset2.end (),intset3.begin ());
copy(intset3.begin(), intset3.end(),\
ostream_iterator<int>(cout, "\n"));
}
Object-Oriented Programming

215

STL 26
Anything that can have the operator () applied to it is a function
object. A functions name is an example of a function object:
#include <algorithm>
using namespace std;
void printing_function (int i)
{
cout << i << ' ';
}
main()
{
int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
for_each(A, A + N, printing_function);
}//for_each is algorithm
Object-Oriented Programming

216

STL 27
Now that you know something about STL, you should be able to
Write larger/more complex C++ program using less effort and time.
STL is a programming library, designed for generic programming in
C++. It is based on templates which are parameterized functions
Or classes.
STL is a library containing many functions and algorithms and a
Number of containers. The only way to learn a new library is to
Extensively explore its features and practice with them. Maybe we
should have started STL sooner than we did, so we could have had
more time using and exploring it.
The book C++: A Complete Reference has a whole chapter on STL,
Including some examples. It also lists all the functions/algorithms
of the STL library. You should consult it for your STL programming.
Object-Oriented Programming

217

Exception Handling
If you recall the first lecture of last year course, it was mentioned
That good programs have certain characteristics such as:
Correctness, timeliness, user-friendly, reliable, stable, maintainable.
Well, for your programs to be really good, they should also be
Robust; which means that your programs should cope with errors.
For example, a program that crashes after invalid input is not a
Robust program. Such a program should check the input for validity
And if it is invalid it should prompt the user for valid input.
Error-handling is a major part of most large-scale programming
Projects and error-handling should be carefully designed and
Implemented. Because if the error-handling design is faulty, your
Program wouldnt be reliable.
Object-Oriented Programming

218

Exception Handling 2
So far, we have followed the traditional method of handling errors;
by returning an error code which can indicate the success or
failure of a function call. But this method of error-handling has at
least two drawbacks/problems:
- code is a lot less readable, because a great part of it is
devoted not to the task itself, but to error situations that are
not frequent. Your programs tend to be both messy and bulky.
- the error has to be handled right in the place where it
generates. This is not desirable, because the error may be
generated in a function called by many different pieces of
code that require different error handling procedures.
Another problem with returning error codes is that the functions
Return value cannot be used for anything else.
Object-Oriented Programming

219

Exception Handling 3
The C++ exception handling mechanism deals with these problems
by not requiring the explicit checking of errors and by separating
exception generation and exception detecting and handling.
The word exception means something that is unusual or something
that does not fit into a general rule. Its a more general term used
for referring to errors. But exceptions are different from
ordinary errors; they only happen occasionally. Examples include:
trying to obtain heap memory when there is none left, trying to
create a file on disk when disk is full, division be zero
The C++ exception-handling mechanism allows the separation of
error-handling from normal code flow. This separation helps
reduce program complexity and aid programmers to be more
productive.
Object-Oriented Programming

220

Exception Handling 4
C++ exception-handling is built around three keywords: try, catch
and throw. When you want to monitor a group of statements for
exceptions you enclose them in a try block. If an exception occurs
within the try block, it is thrown. The exception is caught using
catch and processed. Catch statements must immediately follow
the try blocks. The general form of try and catch are shown here:
try {
//try block
}
catch(type1 arg) {
//catch block
}
catch(type2 arg) {
//catch block
}
//more catch statements
Object-Oriented Programming

221

Exception Handling 5
This example shows how C++ exception handling works:
main()
{
try{
cout<<Inside the try block<<endl;
throw 1;
//throw an exception
cout<<This will not execute<<endl;
}
catch (int i) {
cout<<Caught an exception. No: <<i<<endl;
}
}

As soon as an exception has been thrown, control is passed to the


catch statement and the try block terminates. Catch is not called;
program execution is transferred to it. Program execution continues
with the statements following the catch statement.
Object-Oriented Programming

222

Exception Handling 6
If you throw an exception for which there is no matching catch
Statement, an abnormal program execution may occur. Exceptions
Must be thrown only from within a try block; or from a function
Which is called inside a try block.
Exceptions can be of any type, including user-defined classes:
class my_exception {
public:
char str_what[20];
int what;
my_exception(char * s, int s) {
strcpy(str_what,s); what=e;
}
};
Object-Oriented Programming

223

Exception Handling 7
main(){
int I;
try {
cout<<enter a positive number: <<endl;
cin>>i;
if(i<0)
throw my_exception(Not Positive, i);
}
catch (my_exception e) {
cout<<e.str_what<<: ;
cout<<e.what;
}
}
If a negative number is entered, an object of class my_exception is
created that describes the error.
Object-Oriented Programming

224

Exception Handling 8
As stated earlier, you can have more than one catch statement
associated with a try block. But each catch statement must catch
a different exception type. Only one catch statement is executed
and the rest of catch blocks are ignored. You can also have a
catch statement that catches all exceptions:
void handler(int test) {
try {
if (test==0) throw test;
if (test==1) throw a;
if(test==2) throw 1.22;
}
catch() { cout<<Caught one<<endl;
}
}
main() {
handler(0); handler(1); handler(2); } //3 Caught Ones
Object-Oriented Programming

225

Exception Handling 9
Lets now look at a more useful example of exception handling:
Void divide(int a, int b);
main(){
int i, j;
do{
cout<<Enter numerator: ; cini>>i;
cout<<Enter denominator:; cin>>j;
divide(i, j);
}while(i!=0);
}
void divide(int a, int b) {
try{
if(!b) throw b;
cout<<Result :<<a/b<<endl;
}
catch(int b) {cout<<Cant divide by zero<<endl; }
}
Object-Oriented Programming

226

Exception Handling 10
Because division-by-zero is an illegal operation, the program cannot
Continue if a zero is entered for the second parameter. In this case
The exception is handled by not performing the operation which
Would have caused abnormal program termination. It also notifies
The user of the exception/error.
Then the program asks for two more numbers and thus the error
Has been handled in an orderly way and the user may continue with
The program. This simple example demonstrates what exception
Handling is about: to provide an orderly way of handling errors.
One advantage of this is that your could would simplified: no matter
How many times you call the function divide(), you dont have to
Worry about error-handling, because it is dealt with at one place
Only. This was not the case with functions returning error codes.
Object-Oriented Programming

227

Вам также может понравиться