+ All Categories
Home > Education > Object-Oriented Programming Using C++

Object-Oriented Programming Using C++

Date post: 06-May-2015
Category:
Upload: university-of-salahaddin
View: 4,049 times
Download: 3 times
Share this document with a friend
Description:
This is also from Mr Karim Zebari for OOP programming. Its better to start with simple principals of C++ programming before starting this one.
Popular Tags:
227
1 Object-Oriented Programming Using C++ 2 nd Year Department of Software Engineering College of Engineering University of Salahaddin-Erbil
Transcript
Page 1: Object-Oriented Programming Using C++

1

Object-Oriented Programming Using C++

2nd YearDepartment of Software Engineering

College of EngineeringUniversity of Salahaddin-Erbil

Page 2: Object-Oriented Programming Using C++

2

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’scourse is a pre-requisite for this course. Anyone who has forgotusing C++ is strongly advised to quickly refresh their C++ knowledge.

Object-Oriented Programming

Page 3: Object-Oriented Programming Using C++

3

About This Course, 2

In the first 2 to 3 lectures, we will briefly go over some of theimportant 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 ofthe 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 andlectures 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

Page 4: Object-Oriented Programming Using C++

4

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 lecturesand lab sessions. You should also spend at least 2 hours per week inthe open lab to complete exercises and assignments.

There will be 2 marked assignments for you to perform; each willcarry 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 endof the year.

The final exam will carry 60% of the total grade for this course.

Object-Oriented Programming

Page 5: Object-Oriented Programming Using C++

5

About This Course, 4

I will try to cover most of the syllabus in these lecture notes. Butfor further detail and reference you might find the following textbooks 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 referenceBy: Herbert Schildt, 1998

Copies of these text books are available in the college library for you to borrow.

Object-Oriented Programming

Page 6: Object-Oriented Programming Using C++

6

The Syllabus

We will attempt to cover the following topics during this course:

1. Review of arrays, pointers, structures and file I/O2. Introduction to Object-Oriented Programming3. The Standard String Class4. Classes5. The Big Three6. Function Overloading7. Operator Overloading8. Inheritance 9. Virtual Functions10. Templates11. Exception Handling12. Standard Template Library (STL)

Object-Oriented Programming

Page 7: Object-Oriented Programming Using C++

7

Review of Last Year (arrays)

A C++ array is an indexed collection of variables which are all 1. of the same data type2. referred to by a common name3. 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 is0 and the last element’s index is one less than array-size (4); the most common error associated with arrays is the out-of-bounds-error: you cannot expect marks[5] to have a defined value. Your index is out of bounds.

Object-Oriented Programming

Page 8: Object-Oriented Programming Using C++

8

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 thememory. 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”;

elsecout<<“p and q point to different locations”;

Object-Oriented Programming

Page 9: Object-Oriented Programming Using C++

9

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 strcout<<str[0]; //print Hcout<<p[0]; //print Hcout<<*p; //print Hcout<<*(p+0); //print Hcout<<str[4]; //print Hcout<<*(p+4); //print O

Another example: (the second function is a lot shorter and faster)void print(char *s) void print(char *s){ {

int i; while (*s)for(i=0; s[i]; i++) cout.put(*s++)

cout.put(s[i]); } //*(s++)} //until s[i] is NULL (\0)

Object-Oriented Programming

Page 10: Object-Oriented Programming Using C++

10

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 anythingif (p!=NULL) cout<<p;

Object-Oriented Programming

Page 11: Object-Oriented Programming Using C++

11

Review of Last Year (Structures)

A structure is a collection of related variables. When you define astructure 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 willbe a call by value parameter.

Object-Oriented Programming

Page 12: Object-Oriented Programming Using C++

12

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 thegetline 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 oruntil 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

Page 13: Object-Oriented Programming Using C++

13

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 syntaxin>>str;cout<<str; //will output ‘Write’ on screenin.close();return 0;

}

Object-Oriented Programming

Page 14: Object-Oriented Programming Using C++

14

Review of Last Year (File I/O 2)

When you open a file using the open member function the defaultmode 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 bypassing extra parameters to the open function:

ios::app - opens the file, and allows additions at the endios::trunc - deletes everything in the file ios::nocreate - does not open if the file must be createdios::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

Page 15: Object-Oriented Programming Using C++

15

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 partis 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 mustbe 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

Page 16: Object-Oriented Programming Using C++

16

Some Basics 2

You can write programs in different ways and at different levels. Low level programs, those written with low-level languages or themachine 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 Javaare 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

Page 17: Object-Oriented Programming Using C++

17

Some Basics 3

Programs written in low level languages are understandable by thecomputer and therefore do not need a translation process. Assemblylanguage programs are close to machine language but they do needto be translated to machine language as they are not understandableby the computer. Assemblers are programs which translate fromassembly language to machine language.

Programs written in high level languages are very far from machinelanguage. 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 readyto 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

Page 18: Object-Oriented Programming Using C++

18

Enumeration Data Type

An enumeration type is a type whose values are defined by a set ofconstants of type integer. Lets look at an example:

enum direction { north, east, south, west};

Here we have declared direction to be an enumeration data typewhose 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 inenum 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 makeyour code easier to understand.

Object-Oriented Programming

Page 19: Object-Oriented Programming Using C++

19

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’sname. 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 beconverted 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

Page 20: Object-Oriented Programming Using C++

20

Command Line Arguments 2

In this example we will write a program to open and display a fileon 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 filechar 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

Page 21: Object-Oriented Programming Using C++

21

Formatting Output

Every output stream has a number of member functions used toformat the way data is output. We know three of them already:

out_stream.setf(ios::fixed);//ordinary real formatout_stream.setf(ios::showpoint);//show pointout_stream.precision(2); //set precision to 2

There are more output stream member functions such as:out_stream.setf(ios::showpos);//show plus signout_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

Page 22: Object-Oriented Programming Using C++

22

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 havefunctions 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 thethree functions, the compiler knows which function to call. This canmake large programs easier to read and reduces complexity.

Object-Oriented Programming

Page 23: Object-Oriented Programming Using C++

23

Inline functions

A program that has many function calls can slow down the process ofprogram execution. This is because calling functions is an expensiveoperation 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 thatthey 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 toolarge and called too often, then it will make your program grow insize and this is a disadvantage of inline functions.

inline bool even(int n) {

return (n%2==0); // a small function}

Object-Oriented Programming

Page 24: Object-Oriented Programming Using C++

24

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 wascreated to make programming easier and help the programmer handle more complex programs.

At first, programmers had to write programs using laborious binaryinstructions and data with switches. Later, assembly languages wereinvented 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

Page 25: Object-Oriented Programming Using C++

25

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 inearly 1980s is also a structured language; it also supports object-oriented 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

Page 26: Object-Oriented Programming Using C++

26

Object-Oriented Programming 3

With structured programming you can write quite complex programs.But after a certain point even structured programming or becomesvery hard to follow.

To write larger and more complex programs, a new programmingapproach was invented: object-oriented programming or OO forshort. 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 threeconcepts is said to be an OO programming language. Examples ofOO programming languages are C++, Java, Smalltalk…. Unlike C++, Java is a pure OO programming language.

Object-Oriented Programming

Page 27: Object-Oriented Programming Using C++

27

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 OOprograms consist of objects. An object is similar to an ordinaryvariable 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 thatcan be used and reused in other programs. This also allows forcomposition 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

Page 28: Object-Oriented Programming Using C++

28

Encapsulation

Encapsulation is the binding together of code and data and keepingboth safe from outside interference and misuse. When code anddata 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 otherparts 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 forother parts of your program to access that code/data in the normalway. 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

Page 29: Object-Oriented Programming Using C++

29

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 forfinding the absolute value of a number: abs(), labs() and fabs() forinteger, long and float numbers respectively. In C++ you can usefunction overloading and use the same name for all the 3 functionsthereby reducing complexity.

The general concept of polymorphism is “one interface, multiple methods”. In other words, you use the same method or mechanismto perform a group of related tasks. As we saw with function over-loading, polymorphism helps reduce complexity. Polymorphism canbe applied on both functions and operators as we will see later.

Object-Oriented Programming

Page 30: Object-Oriented Programming Using C++

30

Inheritance

Inheritance is another important feature of OO programming. Withinheritance 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 extrafeatures specific only to itself.

Inheritance provides for hierarchical classification which is veryimportant in making information manageable. For example, a squareis a kind of rectangle; in turn, a rectangle is a kind of closedgeometric shape; in turn, a closed geometric shape is a kind of geometric shape. In each case, the child object inherits all theproperties 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

Page 31: Object-Oriented Programming Using C++

31

The string class 1

C++ has two ways of handling strings. The first, which you saw lastyear, is using the traditional null-terminated character arrays. They are also called c-strings because they were inherited from the Clanguage. 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 ismuch easier and safer than using c-strings.

Object-Oriented Programming

Page 32: Object-Oriented Programming Using C++

32

The string class 2

You can still use the c-strings in your programs as they are moreefficient than using the string class. But when you want ease ofuse, safety and integration into C++ you should use the new stringsof type string.

Variables of type string are called objects, which means that theyhave both data and operations (functions) associated with them. Touse the string class you need to include the header file <string> inyour 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 cansee above. The first creates an empty string object, the secondcreates and initializes a string object and the third one creates a string object from another string object.

Object-Oriented Programming

?

Page 33: Object-Oriented Programming Using C++

33

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

Page 34: Object-Oriented Programming Using C++

34

The string class 4

You can use the << and >> operators to perform input and output. Forexample:

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

Page 35: Object-Oriented Programming Using C++

35

The string class 5

As you can see, string objects are more flexible than c-strings. Youcan use the subscript operators [] for accessing string charactersin 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”); string str(“Dean”);cout<<str[6]; cout<<str.at(6);

For the first version the compiler might not give an error messagealthough 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 theinput stream getline() but works with string objects only.

Object-Oriented Programming

Page 36: Object-Oriented Programming Using C++

36

The string class 6

Let’s look at an example program that checks to determine whethera string of text is a palindrome or not:

#include <iostream>#include <string>using namespace std;void swap(char &a, char &b); //swap two charsbool isPal(const string &str); //check if pal.string reverse(const string &str); //reverses stringsmain(){ 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

Page 37: Object-Oriented Programming Using C++

37

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 thatreversed 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

Page 38: Object-Oriented Programming Using C++

38

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

Page 39: Object-Oriented Programming Using C++

39

The string class 9

…more string functions:str1<str2 str1>str2 //lexicographical comparisonsstr1<=str2 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 manymore 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 havean array of strings as in:

string names[31];

Object-Oriented Programming

Page 40: Object-Oriented Programming Using C++

40

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 str2cout<<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

Page 41: Object-Oriented Programming Using C++

41

Exercises

1. Write a program to display a numbered menu on the screen suchas:

****************************************** 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 afunction to perform the required action. You can use system callsto obtain time and date, for example

system(“date”);will display the computers date on the screen.

Object-Oriented Programming

Page 42: Object-Oriented Programming Using C++

42

Exercises

2. Write a function that takes two integer arrays, of equal size, asparameters. The function asks the user to fill the first array witha 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-indexedlocations 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

Page 43: Object-Oriented Programming Using C++

43

Exercises

4. Using c-strings, write a program that asks the user to type in10 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. Savethe 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 allthe occurrences of the specified word in that file. It should printthe number of occurrences of that word and if the word is notpresent in the file an appropriate message should be displayed. 7. Explain what is encapsulation? polymorphism? inheritance?

Object-Oriented Programming

Page 44: Object-Oriented Programming Using C++

44

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 withspacing corrected, for example the following sentence

Never re-invent the wheel.should be output as

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

Page 45: Object-Oriented Programming Using C++

45

Exercises

11. Write a function that takes a string array as parameter andit 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 ifcalled 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

Page 46: Object-Oriented Programming Using C++

46

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 ofnumeric 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

Page 47: Object-Oriented Programming Using C++

47

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 classpublic:

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 whichyou can use in your programs to declare objects of this new type.Functions and variables declared inside a class are members of thatclass: member functions and member variables.

Object-Oriented Programming

Page 48: Object-Oriented Programming Using C++

48

Classes 2

By default, all member functions and variables declared inside a class are private to that class. This means that they are accessibleonly by other members of that class. Other parts of your programcannot directly access them. Public member functions and variablesare 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 variablepublic: //notice the colon :

void set_a(int num); //public member functionint get_a(); //public member function

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

Object-Oriented Programming

Page 49: Object-Oriented Programming Using C++

49

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 createobjects from it:

myclass ob1, ob2;Two successive colons is called the scope resolution operator.

Object-Oriented Programming

Page 50: Object-Oriented Programming Using C++

50

Classes 4

Now we will write a complete program that uses the class myclass:

//must include class definition heremain(){

myclass ob1, ob2;ob1.set_a(10);ob2.set_a(20);

cout<<ob1.get_a()<<endl;cout<<ob2.get_a()<<endl;

//ob1.a=11; //this would be illegal return 0;

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

Object-Oriented Programming

Page 51: Object-Oriented Programming Using C++

51

Constructors

Your programs’ variables usually require initialization. Sometimes initialization is absolutely necessary and sometimes its not, but it’salways a good idea to initialize your variables. With objects too, youshould use initialization. In fact, most objects require some sort ofinitialization before you can make any use of them.

A constructor is used to do automatic initialization for objects. Aconstructor is a special member function that is called automaticallywhenever an object is created or instantiated. For example:

class myclass{

int a;public:

myclass();void show();

}; //turn over

Object-Oriented Programming

Page 52: Object-Oriented Programming Using C++

52

Constructors 2

… continued

myclass::myclass(){

cout<<“In constructor\n”;a=0;

}void myclass::show(){

cout<<a<<endl;}main(){

myclass ob; //constructor calledob.show(); //will output 0return 0;

}

Object-Oriented Programming

Page 53: Object-Oriented Programming Using C++

53

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 iscalled only when an object is created or declared. It cannot becalled any other time. Also note that for global objects the constructor function is called only once while for local objects it maybe called many time.

It’s 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

Page 54: Object-Oriented Programming Using C++

54

Destructors

An object’s constructor is called when the object is first created.When an object is destroyed its destructor is called. Sometimesit’s necessary to do some things after we finish with an object suchas freeing heap memory or deleting pointers and such. You could dothese tasks in a destructor function that is called automaticallywhen the object goes out of scope: end of program, end of functioncall. The name of a destructor is the name of the class it is part ofpreceded by a ~:

class myclass{

int a;public:

myclass();~myclass();void show();

}; turn over

Object-Oriented Programming

Page 55: Object-Oriented Programming Using C++

55

Destructor 2

… continuedmyclass::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

Page 56: Object-Oriented Programming Using C++

56

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

Page 57: Object-Oriented Programming Using C++

57

An Example 2

… continuedstrtype::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

Page 58: Object-Oriented Programming Using C++

58

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

Page 59: Object-Oriented Programming Using C++

59

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 objectcreated: initialization and freeing up memory are done automaticallywhenever a new object is declared. This is very important as it helps reduce complexity.

Object-Oriented Programming

Page 60: Object-Oriented Programming Using C++

60

Another example

This is an interesting example in which we will use an object of typetimer class to time the interval between when an object of type timer is created and when it is destroyed. When the object’sdestructor 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

Page 61: Object-Oriented Programming Using C++

61

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 ticksmain(){

timer ob;char c;cout<<“Press a key followed by ENTER:”;cin>>c;

} program duration displayed in seconds

Object-Oriented Programming

Page 62: Object-Oriented Programming Using C++

62

Object PointersAs you have seen, you can access members of an object using the dotoperator. 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

Page 63: Object-Oriented Programming Using C++

63

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 havealready created.

Object-Oriented Programming

Page 64: Object-Oriented Programming Using C++

64

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

Page 65: Object-Oriented Programming Using C++

65

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 inform-ation. 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. Whatare 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 usedc) It may not include loops d) It must not be recursive

Object-Oriented Programming

Page 66: Object-Oriented Programming Using C++

66

Exercises

19. You can have overloaded constructor functions as the followingclass definition demonstrates:

class myClass{int x;char c;

public:myClass();myClass(int x, char c);

};Which of the following are legal?

a) myClass ob1(2, ‘h’);b) myClass ob2;c) myClass ob3();d ob1=myClass(6, ‘g’);e) ob1=myClass();f) ob1=myClass;

Object-Oriented Programming

Page 67: Object-Oriented Programming Using C++

67

Exercises

20. Define a class called BankAccount. Declare the following privatedata 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

Page 68: Object-Oriented Programming Using C++

68

Assigning Objects

You can assign one object to another object only if they are both ofthe 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-liningvoid show() {cout<<a<<‘ ‘<<b<<“\n”;}

};main(){

myclass ob1, ob2;o1.set(3, 8);o2=o1; //assign o1 to o2, copies data members a and bo1.show(); //will output: 3 8o2.show(); //will output: 3 8

}

Object-Oriented Programming

Page 69: Object-Oriented Programming Using C++

69

Assigning Objects 2

But assigning objects can be dangerous sometimes. Can you identifythe 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

Page 70: Object-Oriented Programming Using C++

70

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

Page 71: Object-Oriented Programming Using C++

71

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 memorypointed 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 oferror 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

Page 72: Object-Oriented Programming Using C++

72

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

Page 73: Object-Oriented Programming Using C++

73

Objects to functions 2

Objects are passed to functions by value. To have functions modifythe 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

Page 74: Object-Oriented Programming Using C++

74

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. Whena copy of an object is made to be used in a function call, the object’sconstructor is NOT called. Because constructor functions are usuallycalled when initialization needs to be done to the objects data. Whenwe pass an object to a function we don’t want to lose the data or thestate 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

Page 75: Object-Oriented Programming Using C++

75

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 bereleased 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

Page 76: Object-Oriented Programming Using C++

76

Objects to functions 5

…continuedint 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…25Destructing…

Only one call to the constructor is made. However, two calls to thedestructor are made, one for the object’s copy and one for itself.

Object-Oriented Programming

Page 77: Object-Oriented Programming Using C++

77

Objects to functions 6

The fact the destructor of an object, passed to a function, is calledwhen the function terminates can cause some problems. For exampleif the object allocates dynamic memory and releases that memorywhen destroyed, then the object’s copy will free the same memorywhen 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 objectto 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

Page 78: Object-Oriented Programming Using C++

78

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

Page 79: Object-Oriented Programming Using C++

79

Objects to functions 8

…continuedint negative(dynamic ob){

return –ob.get();}main(){

dynamic ob1(-8);cout<<ob1.get()<<endl;cout<<negative(ob1)<<endl;

cout<<ob1.get()<<endl; //errorcout<<negative(ob1)<<endl; //error

}Here, ob1’s destructor is called when the function negative ends andthis causes the dynamic memory pointed to by the original ob to bedestroyed.

Object-Oriented Programming

Page 80: Object-Oriented Programming Using C++

80

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 aclass type as in:

class myclass {int i;

public:myclass(int n) { i=n; cout<<“Constrcuting\n”}~myclass() {cout<<Destructing\n”;}int get() { return i;};

};myclass myfunction() {

myclass ob(9);return ob;

}

Object-Oriented Programming

Page 81: Object-Oriented Programming Using C++

81

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 ismade when the object is returned from the function. A temporaryobject is made which is returned by the function; it is the copy ofthis object whose destructor is called. Again as with objects passedto functions, this situation can also cause problems. And again thesolution for this problem lies in using a copy constructor which wewill study shortly.

Object-Oriented Programming

Page 82: Object-Oriented Programming Using C++

82

Friend Functions

In some situations you may need a function that has access to theprivate members of a class without that function being a member ofthat 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 hasaccess to the private members of two or more different classes.

A friend function is defined like regular, non-member functions asthe 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

Page 83: Object-Oriented Programming Using C++

83

Friend Functions 2

bool isFactor(myclass ob){

if (!(ob.n % ob.d)) return true;

elsereturn 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 towhich the function will be a friend and precede the declaration withthe keyword friend.

Object-Oriented Programming

Page 84: Object-Oriented Programming Using C++

84

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 hasbeen declared inside the function. A friend function cannot directlyaccess a class’s private members.

Note that since a friend function is not a member function it isnot defined using the scope resolution operator; also is not qualifiedby 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 thisin the next slide program. Here we define two classes and define a friend function to access private members of the two classes. Notehow a forward reference is made. A forward reference is neededbecause one class is referred to by another while being defined.

Object-Oriented Programming

Page 85: Object-Oriented Programming Using C++

85

Friend Functions 4

class truck; //forward referenceclass 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

Page 86: Object-Oriented Programming Using C++

86

Friend Functions 5

int faster(car c, truck t){

return c.speed > t-speed;}main(){ car c(“Mazda”, 140);

truck t(5000, 120);if(faster(c, t))

cout<<“Car c is faster than truck t\n”;}A function can be a member function of a class and a friend of another class. When declaring such a function you need to use thescope resolution operator as it is a member function. But in the class to which it is a friend you need to specify that the functionis defined as a member function of another class as in:

friend bool car::faster(truck t);

Object-Oriented Programming

Page 87: Object-Oriented Programming Using C++

87

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 usingfriend 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

Page 88: Object-Oriented Programming Using C++

88

Copy Constructors

Recall that when 1. an object is assigned to another object or when2. 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 causeproblems especially when using pointers and dynamic memory.

Well, a copy constructor can be used to solve the problem for thelast three cases above; for the first we will need to overloadthe 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

Page 89: Object-Oriented Programming Using C++

89

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 initializeanother 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

Page 90: Object-Oriented Programming Using C++

90

Copy Constructors 3

//copy constructorarray(const array &obj);

void put(int i, int j) { //boundary checkif(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

Page 91: Object-Oriented Programming Using C++

91

Copy Constructors 4

main(){

array num(10); //calls normal constructorint i;

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 numarray x=num; //calls copy constructor

for(i=0; i<10; i++) cout<<x.get(i)<<endl; return 0;

}

Object-Oriented Programming

Page 92: Object-Oriented Programming Using C++

92

Default Arguments

Default arguments allow you to give a parameter a default value When no corresponding argument is specified when the function isCalled. Using default arguments is essentially a shorthand form ofFunction 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 0f(9); //a is 9 and b defaults to 0f(8, 7); //a is 8 and b is 7

All default arguments must be to the right of any parameters thatdon’t have defaults, so the following would be illegal:

void f(int a=0, int b); //illegalAlso, you may specify default arguments either in function prototypeor in function definition, not in both ( a C++ restriction)

Object-Oriented Programming

Page 93: Object-Oriented Programming Using C++

93

Default Arguments 2

Default arguments are related to function overloading as you canSee 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

Page 94: Object-Oriented Programming Using C++

94

Default Arguments 3

If you think about it, there is really no need to have two differentfunctions; instead the second parameter can be defaulted to somevalue 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

Page 95: Object-Oriented Programming Using C++

95

this

C++ has a special pointer called this. This is a pointer that is Automatically passed to any member function when it is called andIt is a pointer to the object that generates the function call.

When a member function refers to another member of the classIt does so directly. It does this without qualifying the reference With a class name or object name. But what is actually happeningIs 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

Page 96: Object-Oriented Programming Using C++

96

this 2

main(){

myclass obj;obj.set_a(99);cout<<obj.get_a()<<endl;

}What is really happening behind the scenes is that the memberfunctions get_a and set_a are passed a pointer and they use thispointer 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

Page 97: Object-Oriented Programming Using C++

97

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

Page 98: Object-Oriented Programming Using C++

98

Exercisesvoid 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()

thatreturns true when the printer is in use by either object or falseotherwise. This function is a friend of both classes.

30. When is a constructor function called? A destructor?Object-Oriented Programming

Page 99: Object-Oriented Programming Using C++

99

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

Page 100: Object-Oriented Programming Using C++

100

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

Page 101: Object-Oriented Programming Using C++

101

Exercisesmain(){

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; likethe getline function whose 3rd parameter is a flag)

Object-Oriented Programming

Page 102: Object-Oriented Programming Using C++

102

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 tm_sec; // seconds, 0-60int tm_min; // minutes, 0-59int tm_hour; // hours, 0-23int tm_mday; // day of month, 1-31int tm_mon; // month since Jan, 0-11int tm_year; // years from 1900

//see next page

Object-Oriented Programming

Page 103: Object-Oriented Programming Using C++

103

Handling Time in C++ 2

int tm_wday; // days since Sunday, 0-6int tm_yday; // days since Jan 1, 0-365int tm_isdst; // 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

Page 104: Object-Oriented Programming Using C++

104

Handling Time in C++ 3

time_t time(time_t *time);returns the current calander time of the system. (can be

calledwith 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

Page 105: Object-Oriented Programming Using C++

105

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 timetm *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: 30 12 2001

Sun Dec 30 09:39:09 2001

Object-Oriented Programming

Page 106: Object-Oriented Programming Using C++

106

Operator OverloadingOperator overloading is another important feature of C++ and object-oriented programming. It allows you to give new meaningto C++ operators relative to classes that you define.

Operator overloading is similar to function overloading. The sameWay that function overloading helps us write better programs,Operator overloading also helps you write better programs andReduce complexity.

When an operator is overloaded, that operator loses none of itsOriginal 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

Page 107: Object-Oriented Programming Using C++

107

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

Page 108: Object-Oriented Programming Using C++

108

Operator Overloading 3

Most C++ operators can be overloaded: =, ==, <,>,<=,>=,+,-,/,*,<<,>>,!....When a member operator function overloads an operator, theFunction 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 theOperator function.

Suppose we have a class called coord that represents a coordinatesPoint on the plane and we want to overload the ‘+’ binary operatorFor 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

Page 109: Object-Oriented Programming Using C++

109

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

Page 110: Object-Oriented Programming Using C++

110

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

Page 111: Object-Oriented Programming Using C++

111

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 relativeto 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 behaviorto the original operator’s. Following this rule will make your programseasier to follow and read.

Object-Oriented Programming

Page 112: Object-Oriented Programming Using C++

112

Operator Overloading 7

We saw on slide 104, how we can overload the + operator relativeto 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 built-in 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 cannothave a statement like o2=1+o1, because the left-operand is theimplicit operand passed to the operator function (the right-handoperator is passed to the function as an argument).

Object-Oriented Programming

Page 113: Object-Oriented Programming Using C++

113

Operator Overloading 8

The solution to this is using friend operator functions instead. A friend function does not have a this pointer (only member functionsdo) This means that in the case of a binary operator, both operandsmust be passed to the function and for unary operators, the singleoperand is passed.

The main reason for using friend operator functions is that theylet you mix objects with built-in types, especially when the right-hand side is a built-in type ( we could not do this using memberoperator functions)class coord {

int x, y;public:

coord() {x=0, y=0;}coord(int i, int j) {x=i; y=j;

Object-Oriented Programming

Page 114: Object-Oriented Programming Using C++

114

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

Page 115: Object-Oriented Programming Using C++

115

Operator Overloading 10 (Assignment Operator)

By default, when the assignment operator is applied to an object, abitwise copy of the object on the right is put into the object on theleft. 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 notdesirable; 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 neededdelete [] p; p=new char [ob.len];if(!p) exit(1);}

len=ob.len;strcpy(p, ob.p);return *this;

}

Object-Oriented Programming

Page 116: Object-Oriented Programming Using C++

116

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

Page 117: Object-Oriented Programming Using C++

117

Exercises

37. Add two constructor functions to the following class so thatBoth declarations inside main() are valid.

class samp {

int a;public:

// add 2 constructors here};main(){

samp ob(99); //initialize ob’s a to 99samp ob_array[10];//non-initialize 10-member array

//…}

Object-Oriented Programming

Page 118: Object-Oriented Programming Using C++

118

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 soThat un-initialized objects can be created. (when creating un-Initialized 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

Page 119: Object-Oriented Programming Using C++

119

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 itprobably a bad idea?

43. Create a class called rational which is used to represent rationalnumbers: ½, ¾, etc. So your class will have two private datamembers. Add the following member functions:-a default constructor -a parameterized constructor-overloaded + operator-overloaded – operator-overloaded / operator-overloaded * operator

Object-Oriented Programming

Page 120: Object-Oriented Programming Using C++

120

Exercises

44. True or false: when a binary operator is overloaded, the leftOperand is passed implicitly to the function and the right operandis passed as an argument?

45. Overload the == operator relative to the rational class set asExercise 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 oftype rational (either on left or right of operand)

Object-Oriented Programming

Page 121: Object-Oriented Programming Using C++

121

Exercises

49. How do friend operator functions differ from member operatorFunctions? 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 typesof operators:

- string concatenation using + operator- string assignment using the = operator- string comparisons using <,> and =

Object-Oriented Programming

Page 122: Object-Oriented Programming Using C++

122

Inheritance

Inheritance is one of the three principles of OO programming. In the next few slides we will see how inheritance supports theconcept of hierarchical classification and provides support forpolymorphism.

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 tothe 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 thederived class. Generally, the process of inheritance starts with defining a base class which include all qualities/properties commonto any derived class. (Parent class/child class)

Object-Oriented Programming

Page 123: Object-Oriented Programming Using C++

123

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

Page 124: Object-Oriented Programming Using C++

124

Inheritance 3

main(){

D ob;ob.set_i(10); //access base class functionob.set_j(20); //access derived class functioncout<<mutl()<<endl; //display 200return 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 bedirectly 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

Page 125: Object-Oriented Programming Using C++

125

Inheritance 4

The general form of one class inheriting another isclass 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 bythe 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

Page 126: Object-Oriented Programming Using C++

126

Inheritance 5

There are times when you want a derived class to have access toprivate 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 afterdeclaring private members and before public members. When aprotected 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 classbecome private members of the derived class.

If a base class is inherited as protected, then public and protectedmembers of the base class become protected members of the derived class. Of course, private members of the base class remainprivate to the base class.

Object-Oriented Programming

Page 127: Object-Oriented Programming Using C++

127

Inheritance 6

Let’s look at an example:class samp{

int a;Protected: //still private to samp but accessible

int b; //by derived classesPublic:

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 privateob.c=4; //legalcout<<geta()<<“ “<<getb()<<“ “<<ob.c<<endl;

}

Object-Oriented Programming

Page 128: Object-Oriented Programming Using C++

128

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 accessmain(){ derived ob; ob.setab(1,2); ob.setc(3); ob.showabc(); }//but a and b inaccessible outside class

Object-Oriented Programming

Page 129: Object-Oriented Programming Using C++

129

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 accessmain(){ derived ob; ob.setc(3); ob.setab(1,2); //Error: why? ob.showabc(); }

Object-Oriented Programming

Page 130: Object-Oriented Programming Using C++

130

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 totake the same argument. It’s also possible for the derived classto ignore any arguments and pass them to the base class.

Object-Oriented Programming

Page 131: Object-Oriented Programming Using C++

131

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

Page 132: Object-Oriented Programming Using C++

132

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 calledIn 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

Page 133: Object-Oriented Programming Using C++

133

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) { b=x;}int getb() {return b;}

};class D2 : public D1 {

int c; //continued…

Object-Oriented Programming

Page 134: Object-Oriented Programming Using C++

134

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 1D1 inherits B1 as public and so B1’s public members become D1’spublic members and in turn D1’s public members become public members of D2 since D2 inherits D1 as public and hence the waygeta() and getb() are accessed in show() in D2; they are used directly since they have become public members of D2.

Object-Oriented Programming

Page 135: Object-Oriented Programming Using C++

135

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

Page 136: Object-Oriented Programming Using C++

136

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 1when a derived class derived3 inherits from two classes derived1and 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

Page 137: Object-Oriented Programming Using C++

137

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 presentob.y=2; ob.z=3;cout<<“Product is: “<<ob.product<<endl; }

Object-Oriented Programming

Page 138: Object-Oriented Programming Using C++

138

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); b) o2.getab(i, j); c) o1.c=10; d) o2.c=10

Object-Oriented Programming

Page 139: Object-Oriented Programming Using C++

139

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

Page 140: Object-Oriented Programming Using C++

140

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

Page 141: Object-Oriented Programming Using C++

141

Exercises

58. Write a constructor for C so that it initializes k and passes onarguments 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

Page 142: Object-Oriented Programming Using C++

142

Exercises

59. Create a base class called building that stores the number offloors a building has, the number of rooms and its total square area.Create a derived class called house that inherits building and alsostores: 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 anoperator that may not be inherited. Give the reason why it maynot be inherited by derived classes.

Object-Oriented Programming

Page 143: Object-Oriented Programming Using C++

143

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

Page 144: Object-Oriented Programming Using C++

144

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

Page 145: Object-Oriented Programming Using C++

145

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 seethey can make writing complex programs easier.

Object-Oriented Programming

Page 146: Object-Oriented Programming Using C++

146

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 startfile>>s2; //of streamcout<<s2<<file.tellp()<<endl; //current position offile.close(); //file pointer

}

Object-Oriented Programming

Page 147: Object-Oriented Programming Using C++

147

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 charactercout<<ch<<endl;file.putback(ch);file.get(ch);cout<<ch<<endl;

}

Object-Oriented Programming

Page 148: Object-Oriented Programming Using C++

148

Exercises

66. Which program is ‘better’? Explain why (Hint: Encapsulation)

class X { class Y { public: int x;

X() {x=0;} public:int x; Y() { x=0;}

void set(int k) {x=k;}}; };

main() main(){ {

X ob; Y ob;b.x=7; ob.set(7);

} }

Object-Oriented Programming

Page 149: Object-Oriented Programming Using C++

149

Polymorphism (Virtual Function)

Polymorphism means “one interface, multiple methods”; C++ supportspolymorphism in two ways: first, using overloaded functions and operators (also called static binding) and second, using virtualfunctions which is achieved at run time (also called late binding ordynamic 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, naturalp=&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

Page 150: Object-Oriented Programming Using C++

150

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

Page 151: Object-Oriented Programming Using C++

151

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 indirectlyd_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

Page 152: Object-Oriented Programming Using C++

152

Polymorphism (Virtual Function) 4

A virtual function is a class member function that is declared insidea base class and redefined by a derived class. Just precede thefunction’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

Page 153: Object-Oriented Programming Using C++

153

Polymorphism (Virtual Function) 5

Now let’s see what happens when a virtual function is called usinga pointer. Remember that a base class pointer can be used to pointto 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 throughthat pointer, the compiler decides which version of that functionto 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

Page 154: Object-Oriented Programming Using C++

154

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

Page 155: Object-Oriented Programming Using C++

155

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 thesame as function overloading. There is a special term used forreferring to redefined virtual functions: overridden. Can you thinkof the differences between overridden and overloaded functions?

The important point to know is this: it is the type of object beingpointed to by a base class pointer that determines which versionof an overridden virtual function will be executed, and this decisionis made at runtime.

Object-Oriented Programming

Page 156: Object-Oriented Programming Using C++

156

Polymorphism (Virtual Function) 8

One of the main applications and uses of runtime polymorphism andvirtual 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 awindow 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

Page 157: Object-Oriented Programming Using C++

157

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 atleast 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

Page 158: Object-Oriented Programming Using C++

158

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

Page 159: Object-Oriented Programming Using C++

159

Polymorphism (Virtual Function) 11

Note: The following is taken from the C++ FAQ: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

C+

+F

AQ

on

soft-en

g.lo

cal

Page 160: Object-Oriented Programming Using C++

160

Virtual Function (Type Compatibility)

As you know, C++ is a strongly typed language which implies thatYou 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

Page 161: Object-Oriented Programming Using C++

161

Virtual Function (Type Compatibility) 2

Now, anything that is a student is also a person and the followingshould be legal:

s.name=“X”; s.year=2; p=s;C++ allows this but the reverse is not possible. Although this sortof assignment is ok, the value of the member variable year is lost(the slicing problem):

cout<<p.year; //will generate an errorThis 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: 2Why: Because the function print() is virtual.

Object-Oriented Programming

Page 162: Object-Oriented Programming Using C++

162

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 asvirtual in Derived.

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

• If Base is an abstract class, then all member functions of BaseMust be pure virtual functions.

Object-Oriented Programming

Page 163: Object-Oriented Programming Using C++

163

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 mustOverride 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

Page 164: Object-Oriented Programming Using C++

164

Exercises

main(){

D* pD=new D;Base* pB=pD;E* pE=new E;

pB->F(); //line 1pB->G(); //line 2pB->H(); //line 3pB->I(); //line 4

pD->F(); //line 5pD->G(); //line 6pD->I(); //line 7pD->J(); //line 8

//see next slide

Object-Oriented Programming

Page 165: Object-Oriented Programming Using C++

165

Exercises

pB=pE;pD=pE;

pB->F(); //line 9pB->G(); //line 10pB->H(); //line 11pB->I(); //line 12

pD->F(); //line 13pD->J(); ..line 14

pE->F(); //line 15pE->H(); //line 16

}• Line 1:

1) Base::F() 2) D::F() 3) E::F() 4) None

Object-Oriented Programming

Page 166: Object-Oriented Programming Using C++

166

Exercises

75. Line 2:1) Base::G() 4) Base::H() 7) 2 and then 42) D::G() 5) D::H() 8) 2 and then 53) E::G() 6) 1 and then 4 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

• Line 5:• Base::F() 2) D::F() 3) E::F() 5) None

• Line 7:1) Base::I() 2) D::I() 3) E::I() 4) None

Object-Oriented Programming

Page 167: Object-Oriented Programming Using C++

167

Exercises

80. Line 6:1) Base::G() 4) Base::H() 7) 2 and then 42) D::G() 5) D::H() 8) 2 and then 53) E::G() 6) 1 and then 4 9) None

81. Line 8:1) Base::J() 2) D::J() 3) E::J() 4) None

82. Line 9:1) Base::F() 2) D::F() 3) E::F() 4) None

83. Line 10:• Base::G() 4) Base::H() 7) 2 and then 5• D::G() 5) D::H() 8) 3 and then 5• E::G() 6) 2 and then 4 9) None• Line 11:1) Base::H() 2) D::H() 3) E::H() 4) None

Object-Oriented Programming

Page 168: Object-Oriented Programming Using C++

168

Exercises

85. Line 12:1) Base::I() 2) D::I() 3) E::I() 4) None

86. Line 13:1) Base::F() 2) D::F() 3) E::F() 4) None

87. Line 14:1) Base::J() 2) D::J() 3) E::J() 4) None

88. Line 15:1) Base::F() 2) D::F() 3) E::F() 4) None

85. Line 16:1) Base::H() 2) D::H() 3) E::H() 4) None

Object-Oriented Programming

Page 169: Object-Oriented Programming Using C++

169

Exercises

90. Based on the class definitions given on slide 160, what is theoutput 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

Page 170: Object-Oriented Programming Using C++

170

Templates

Using templates, you can define functions and classes which haveparameters for their type names. This will allow you to writegeneric functions and classes. Here is an example of a template function:Template<class T> //T is parameter for typevoid 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

Page 171: Object-Oriented Programming Using C++

171

Templates 2

The output of the program is:2 1b a

The compiler creates a definition for each type that you use in theprogram. It will not however create a definition of each possibleType 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 anduser-defined structs and classes.

The idea of function templates is that some algorithms are genericin nature, that is they apply regardless of the data type used. Theswap function is one such example. Another example is a function tofind the maximum of two values or a sorting function.

Object-Oriented Programming

Page 172: Object-Oriented Programming Using C++

172

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. FirstLets 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

Page 173: Object-Oriented Programming Using C++

173

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

Page 174: Object-Oriented Programming Using C++

174

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; let’s now look at a more practical example involving a template class definition.

Object-Oriented Programming

Page 175: Object-Oriented Programming Using C++

175

Template 6

In this example, we will define a template class whose objects arelists. 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

Page 176: Object-Oriented Programming Using C++

176

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

Page 177: Object-Oriented Programming Using C++

177

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

Page 178: Object-Oriented Programming Using C++

178

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

Page 179: Object-Oriented Programming Using C++

179

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 parametertype (called the base type) and not a specific type.

In this example, an array was used to represent a list. But arraysare not ideal in situations where you don’t know in advance how manyitems they will store. Linked lists, as you know, solve this problem

Object-Oriented Programming

Page 180: Object-Oriented Programming Using C++

180

Templates 11

Template classes, like template functions are useful when theycontain logic which is general as you saw in the previous example. Here is another example in which a generic stack class is created which can be a stack of any type of objects:

#define SIZE 10 //define a constant

Template <class T> class stack {T stack1[size];int tos; //index of top of stack

Public:stack() { tos=0;}void push(T obj);T pop();

};

Object-Oriented Programming

Page 181: Object-Oriented Programming Using C++

181

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

Page 182: Object-Oriented Programming Using C++

182

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

Page 183: Object-Oriented Programming Using C++

183

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 genericfunctions 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 ofitems; 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

Page 184: Object-Oriented Programming Using C++

184

Static Class Members

Class member variables can be declared as static which means that only one copy of that variable exits, no matter how many objectsOf that class are created. This static member variable is sharedBetween all the objects of that class. Also, that variable can beUsed by any class derived form that base class.

It is possible to access a class static member variable even beforeAn object of that class is created. It’s like a global variable whoseIs scope is restricted to the class in which it is declared.

But when you declare a static data member, you are not defining it.You must provide a definition for it outside the class. Also note,that all static numerical data members are initialized to zero by default. You can of course initialize a static data member to any Value you want.

Object-Oriented Programming

Page 185: Object-Oriented Programming Using C++

185

Static Class Members 2

The principal reason static data members are used is to prevent theneed for global variables. As you know, classes that rely on globalVariables break the encapsulation rule, which is very fundamental toOO programming. class myclass {

static int i;public:

void set(int n) {i=n;} int get() {return i;}};int myclass::i;main() {

myclass::i=12; //no object is referencedmyclass o1, o2;//o1.set(12); //access through functioncout<<“o1.i : ”<<o1.get()<<‘\n’; //print 11cout<<“o2.i :”<<o2.get()<<‘\n’; //print 11

}

Object-Oriented Programming

Page 186: Object-Oriented Programming Using C++

186

Static Class Members 3

One interesting use of static data members is when you want toCoordinate access to some resource (file, array, variable, printer, connection) between several objects.

Another use is when you want to keep track of the number of Objects that are in existence at any time. Lets look at an exampleWhich demonstrates this:

class test {static int count;

publci:test() { count++;}~test() { count--;}int getCount() {return count;};

};

Object-Oriented Programming

Page 187: Object-Oriented Programming Using C++

187

Static Class Members 4

main() {test o1, o2, o3;cout<<o1.getcount()<<endl;test *p; p=new test;cout<<o1.getCount(); delete p;cout<<o1.getcount();

}

The first output statement will output: 3The second one will output: 4The last one will output: 3

You can also have static member functions but they are uncommonAnd not of much use.

Object-Oriented Programming

Page 188: Object-Oriented Programming Using C++

188

Namespaces

Scope is the section of the program where a name has a meaning. The more localised variables are the better. There's • file scope - entities can be made visible only to entities in the same file.• function scope - entities can be made visible only to the function they're created in.• block scope - delimited by ' {' and ' }'.• class scope - entities can be made visible only to the class they're created in.• namespaces - A namespace is like a class that has no functionality. Only used for creating a new name space. You can put an entity into a namespace by doing something like:namespace test {int i;}

Object-Oriented Programming

Page 189: Object-Oriented Programming Using C++

189

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

Page 190: Object-Oriented Programming Using C++

190

Namespaces 3

The main reason for using namespaces is this: in large programmingProjects, the possibility of name clashes increases. DifferentProgrammers 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 probabilityOf name clashes with other programmers.

Looking back at the namespace we created (test) we can access itsMembers in three ways:

1) by specifying the name using the scope resolution operator2) 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

Page 191: Object-Oriented Programming Using C++

191

Namespaces 4

Use the using directive: using namespace test;This will make all the test namespace names available for use and you don’t 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

Page 192: Object-Oriented Programming Using C++

192

Standard Template Library (STL)

After studying this topic, you may ask: why did we not start C++With this topic? The reason you may ask this question is thatSTL makes C++ programming so much easier and productive. ButYou would not have appreciated its power until you did some Basic programming and gradually introduced to STL.

C++ templates are the basis of STL. STL is about generic Programming. It has many many classes, methods, and functions Which you can easily use in your programs.

We will not cover All the details of the package, instead we will concentrate on the1) Ideas and concepts of the package2) Look at the main features of the package• Look at some examples.

Object-Oriented Programming

Page 193: Object-Oriented Programming Using C++

193

STL 2

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

i

k j

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

int, char, double…

sort, search, swap… Array, list, queue…

Page 194: Object-Oriented Programming Using C++

194

STL 3

Template functions, the i-axis can be dropped and only j*k versionsOf code would be needed. Next, if you make your algorithms workOn arrays and lists and …, only j+k versions of code would be needed.

STL accomplishes this and thus simplifies the software developmentProcess. STL consists of five main components:

1) Algorithms: computational procedure that is able to work on different containers2) Container: object that can hold collection of other objects3) Iterator: abstraction of access to containers so that an algorithm can work on different containers4) Function Object: a class that has the function call operator (operator ()) defined5) Adapter: encapsulates a component to provide another interface

Object-Oriented Programming

Page 195: Object-Oriented Programming Using C++

195

STL 4

An example is in place:

#include <iostream>#include <vector>using namespace std;

main(){

vector<int> v; //declare an array containerv.push_back (3); //append 3 to the arrayv.push_back (7);v.push_back (2);vector<int>::iterator first=v.begin (); //iteratorvector<int>::iterator last=v.end (); //iteratorwhile(first !=last)

cout<<*first++<<" ";}

Object-Oriented Programming

Page 196: Object-Oriented Programming Using C++

196

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 containerv.push_back (‘a’); //append 3 to the arrayv.push_back (‘f’);v.push_back (‘c’);vector<char>::iterator first=v.begin (); //iteratorvector<char>::iterator last=v.end (); //iteratorsoft(first,last); //sort the arraywhile(first !=last)

cout<<*first++<<" ";}

Object-Oriented Programming

Page 197: Object-Oriented Programming Using C++

197

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

Page 198: Object-Oriented Programming Using C++

198

STL 7

Yet one more example:#include <iostream> #include <vector> #include <algorithm>main(){ vector<double> a;

a.empty() ? cout<<“Empty” : cout<<“Not empty”; //emptyvector<string> v(2,”string”);vector<string> w(2, “word”);v.swap(w); //swap v and wcout<<v[0]<<endl; //wordvector<int> z(3,5);z.push-back(8);cout<<z.front()<<“ “<<z.back()<<endl; //5 8cout<<z.size()<<endl; //4z.pop-back()<<endl; //5 5 5cout<<z.size()<<endl; //3cout<<z.back()<<endl; //5

}

Object-Oriented Programming

Page 199: Object-Oriented Programming Using C++

199

STL 8

And another example: (the insert & erase functions)#include <iostream> #include <vector> main(){

vector<int> v; //vesrion 1 of insertv.insert(v.begin(),6);//first argument is an iteratorcout<<v.capacity()<<endl;cout<<v[0]<<endl;vector<int> w;w.insert(w.begin(), 2, 9); //9 9vector<int> x(1,3);x.insert(x.end(), v.begin(),v.end()); // 3 9 9vector<float> z(4, 7.5); //7.5 7.5 7.5 7.5z.insert(z.begin (),44); //44 7.5 7.5 7.5z.insert(z.end (),66); //44 7.5 7.5 7.5 66z.erase(z.begin()); //7.5 7.5 7.5 66z.erase(z.begin(),z.end()); //same as v.clear()

}

Object-Oriented Programming

Page 200: Object-Oriented Programming Using C++

200

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

Page 201: Object-Oriented Programming Using C++

201

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 oneor 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

Page 202: Object-Oriented Programming Using C++

202

STL 11

Consider the following code fragment:

vector<int> v(5,1); //1v.push_back(5); //2v.insert(v.begin()+2, 7); //3

//1

//2

? //3

Can you say what will the vector v will look like after line 3? Insertin the middle is expensive. So is removing from the middle, becauseelements would have to be relocated in memory.

Object-Oriented Programming

1 1 1 1 1

1 1 1 1 1 5

Page 203: Object-Oriented Programming Using C++

203

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

Page 204: Object-Oriented Programming Using C++

204

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

Page 205: Object-Oriented Programming Using C++

205

STL 14

A list container example:main(){

list<int> l; l.push_front(1); l.push_front (2);l.push_front(3);cout<<*l.begin ()<<endl<<cout<<*--l.end ()<<endl;list<int>::iterator first=l.begin(),second=++l.begin();list<int>::iterator last=l.end ();cout<<*second<<endl; //see last linefor(int i=0; i<2; i++) first++;l.insert (first,18);first=l.begin ();while(first!=last){

cout<<*first<<" "; first++;}cout<<l.size(); //4cout<<*second<<endl; //points to same location

}

Object-Oriented Programming

Page 206: Object-Oriented Programming Using C++

206

STL 15

Another list container example:int main(){

list<int> l1, l2;l1.push_front(1); //1l1.push_back(2); //2 1l1.push_front(3); //2 1 3l1.push_front(2); //2 1 3 2l1.sort(); // 3 2 2 1list<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 l2l1.swap(l2); //swap the contents of l1 and l2l2.remove(3); //delete 3 (and duplicates if any)

}

Object-Oriented Programming

Page 207: Object-Oriented Programming Using C++

207

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); //algortithmif (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

Page 208: Object-Oriented Programming Using C++

208

STL 17

An iterator is an object that encapsulates the state and behaviour necessary to iterate over a container. It behaves differently foreach container, but the interface masks the differences and makesit 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

++iteratorcontainer

begin() *iterator end()

Object-Oriented Programming

Page 209: Object-Oriented Programming Using C++

209

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 alsodefine 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

Page 210: Object-Oriented Programming Using C++

210

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

Page 211: Object-Oriented Programming Using C++

211

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

Page 212: Object-Oriented Programming Using C++

212

STL 21

Now let’s look at how STL sets work. An STL set is a mathematicalSet which cannot have multiple values. In STL, set members areSorted 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"));

} //what’s the output???

Object-Oriented Programming

Page 213: Object-Oriented Programming Using C++

213

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

Page 214: Object-Oriented Programming Using C++

214

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

Page 215: Object-Oriented Programming Using C++

215

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

Page 216: Object-Oriented Programming Using C++

216

STL 26

Anything that can have the operator () applied to it is a function object. A function’s 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

Page 217: Object-Oriented Programming Using C++

217

STL 27

Now that you know something about STL, you should be able toWrite larger/more complex C++ program using less effort and time.

STL is a programming library, designed for generic programming inC++. It is based on templates which are parameterized functionsOr classes.

STL is a library containing many functions and algorithms and a Number of containers. The only way to learn a new library is toExtensively explore it’s 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

Page 218: Object-Oriented Programming Using C++

218

Exception Handling

If you recall the first lecture of last year course, it was mentionedThat 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 validityAnd if it is invalid it should prompt the user for valid input.

Error-handling is a major part of most large-scale programmingProjects and error-handling should be carefully designed and Implemented. Because if the error-handling design is faulty, yourProgram wouldn’t be reliable.

Object-Oriented Programming

Page 219: Object-Oriented Programming Using C++

219

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 function’sReturn value cannot be used for anything else.

Object-Oriented Programming

Page 220: Object-Oriented Programming Using C++

220

Exception Handling 3The 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. It’s a more general term used

for referring to errors. But exceptions are different fromordinary 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

Page 221: Object-Oriented Programming Using C++

221

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 occurswithin 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

Page 222: Object-Oriented Programming Using C++

222

Exception Handling 5

This example shows how C++ exception handling works:main(){

try{cout<<“Inside the try block”<<endl;throw 1; //throw an exceptioncout<<“This will not execute”<<endl;

}catch (int i) {

cout<<“Caught an exception. No: “<<i<<endl;}

}As soon as an exception has been thrown, control is passed to thecatch statement and the try block terminates. Catch is not called;program execution is transferred to it. Program execution continueswith the statements following the catch statement.

Object-Oriented Programming

Page 223: Object-Oriented Programming Using C++

223

Exception Handling 6

If you throw an exception for which there is no matching catchStatement, an abnormal program execution may occur. ExceptionsMust be thrown only from within a try block; or from a functionWhich 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

Page 224: Object-Oriented Programming Using C++

224

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

Page 225: Object-Oriented Programming Using C++

225

Exception Handling 8

As stated earlier, you can have more than one catch statementassociated with a try block. But each catch statement must catcha different exception type. Only one catch statement is executedand 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 One’s

Object-Oriented Programming

Page 226: Object-Oriented Programming Using C++

226

Exception Handling 9

Let’s 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<<“Can’t divide by zero”<<endl; }

}

Object-Oriented Programming

Page 227: Object-Oriented Programming Using C++

227

Exception Handling 10

Because division-by-zero is an illegal operation, the program cannotContinue if a zero is entered for the second parameter. In this caseThe exception is handled by not performing the operation which Would have caused abnormal program termination. It also notifiesThe user of the exception/error.

Then the program asks for two more numbers and thus the errorHas been handled in an orderly way and the user may continue withThe program. This simple example demonstrates what exceptionHandling is about: to provide an orderly way of handling errors.

One advantage of this is that your could would simplified: no matterHow many times you call the function divide(), you don’t have to Worry about error-handling, because it is dealt with at one placeOnly. This was not the case with functions returning error codes.

Object-Oriented Programming


Recommended