Object-Oriented Programming Using C++
2nd Year
Department of Software Engineering
College of Engineering
University of Salahaddin-Erbil
1
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 year’s
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
2
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
3
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
4
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
5
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
6
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 element’s index is
0 and the last element’s 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
7
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
8
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++)
9
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 program’s
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++ it’s 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++ it’s 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.
It’s 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 it’s 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
Let’s 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
//str2’s 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 str2’s 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 Today’s Date
*
* 2. Display Time
*
* 3. Display Both Time and Date
*
* 4. Exit
*
* Enter a number 1 – 4:
*
*****************************************
In response to the user’s 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. Let’s look at an example:
class myclass
{
int a;
//private member variable
public:
//notice the colon :
void set_a(int num);
//public member function
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 it’s
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 3
Note that the constructor myclass has the same name as the class
it is part of and has no return type. It’s 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.
It’s also possible to have parameterized constructor functions:
(from previous example)
myclass::myclass(int x)
{
cout<<“In Constructorn”
a=x;
}
myclass ob(0);
ob.show();
//will output 0
Object-Oriented Programming
53
Destructors
An object’s constructor is called when the object is first created.
When an object is destroyed its destructor is called. Sometimes
it’s 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 constructorn”;
a=10;
}
myclass::~myclass()
{
cout<<“In Destructorn”
}
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 errorn”;
exit(1);
}
*p=‘n’;
//same as p[0]=‘n’
len=0;
}
strtype::~strtype()
{
cout<<“Freeing memoryn”;
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 object’s
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 function’s 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 book’s title, author, year and number of
copies on hand. Use a public member function store() to store a
book’s 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 account’s 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 errorn”; exit(1); }
strcpy(p, ptr);
}
Object-Oriented Programming
69
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 object’s 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 object’s 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 object’s constructor called when the copy is made?
2. Is the object’s 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 object’s
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 don’t 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 it’s 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 object’s 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 object’s 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 object’s 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 failuren”;
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, ob1’s 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<<“Constrcutingn”}
~myclass() {cout<<Destructingn”;}
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 8n”;
else cout<<<<“4 is a not factor of 8n”;
}
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 class’s 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 class’s 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 tn”;
}
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 copy’s constructor called? Is the
copy’s 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
don’t 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
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
Let’s 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 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;
}
Don’t forget that you can also overload relational and logical
operators. Your overloaded operators should have a similar behavior
to the original operator’s. 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 class’s
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 ob’s 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
Let’s 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.
It’s 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
Let’s 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 class’s constructor expects arguments then these
arguments must be passed through the derived class’s constructor.
The general form of the derived class’s constructor is:
derived_class(arg-list) : base (arg-list)
{
//body
}
It’s possible for both the base class and the constructor class to
take the same argument. It’s 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 B1’s public members become D1’s
public members and in turn D1’s 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
function’s 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 let’s 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 window’s
title bar, on a window’s status bar, on a text-box, on a…. Your
program must have a function that responds to these events and
it’s 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 that’s 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 wouldn’t 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