OO C++ Notes
OO C++ Notes
2nd Year
Department of Software Engineering
College of Engineering
University of Salahaddin-Erbil
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.
Object-Oriented Programming
10
11
12
13
For example:
ofstream out(text.txt, ios::app);
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 types are not used very often but can sometimes make
your code easier to understand.
Object-Oriented Programming
18
19
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
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);
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
31
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
33
34
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
36
37
38
str1.find(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
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:
*
*****************************************
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.
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);
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
};
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
};
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;
}
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;
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;
}
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;
}
63
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);
};
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);
}
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;;
}
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
80
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;
}
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;
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
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
103
104
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
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:
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();
}
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();
}
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
};
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;
}
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
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
//---->
150
151
152
153
//----->
154
155
156
157
158
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
160
161
Exercises
(For question 67---73, suppose an inheritance hierarchy with a base class Base and a
derived class Derived. True or False)
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
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
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
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
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
184
185
186
187
Namespaces
Scope is the section of the program where a name has a meaning.
The more localised variables are the better. There's
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
192
STL 2
Before delve into the details of STL, consider the following diagram:
i
k
sort, search, swap
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();
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;
}
}
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