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

Lab Manual

For

Engineering Lab II Object Oriented Programming Module ECE 1201 Semester I 2007/2008

Name Student ID Name of Instructor

: ____________________ : ____________________ : ____________________

ECE 1201:Object Oriented Programming module

Version2.0

Table of Contents General Guidelines and Rules..................................6


[A]: Guidelines.................................................................................................... 6 [B]: Rules....................................................................................................... ....8 .

Course Outline......................................................11 Chapter [1]: Introduction to OOP Lab.....................14 Chapter [4]: Operator Overloading.........................52
Can you try to implement it as non-member function? (Hint: Refer to 4.6.2) Now, lets see the last possibility which is:........................................................................62 Can you guess whether we should implement it as member function or nonmember function? Why?...........................................................................................63 4.6.4Overload insertion operator, <<.......................................................................63 This section will try to eliminate print() member function that we have earlier by overloading insertion operator, <<, but maintaining the purpose which is to print out the fraction object in this form of output, assume fraction object1(4,5), example of output: .................................................................................................................63 . 4/5....................................................................................................... ................63 . Where do you normally use insertion operator, <<? Assume we have these lines of codes:.............................................................................................................. .........64 . cout<< I love programming.. it challenges my thinking capabilities..;.................64 What is the expected output? In dealing with class or user-defined data type, we have to also overload this insertion operator when we want to use it with the objects of our class. Like what we have done before, calling print() function from object a,...................................................................................... .............................64 . a.print();.......................................................................................... .....................64 . which prints out the object of a in terms of X/Y, we want to use the following line of code that produces the same output........................................................................64 cout<<a;.................................................................................................... ..........64 . Doesnt it look simpler? Well, some issues that might arise here:............................64 1.In what way can we overload it? As member function or non-member friend function?.................................................................................................................... 4 6 2.What should be the arguments for operator<<() function?..................................64 3.What should be the return type?...........................................................................64 Chapter [5]: Inheritance................................................................................. ...........66 Chapter [6]: Polymorphism.......................................................................................82

Appendix A: C++ Reserved Words.........................94 Appendix B: ASCII Character Set............................96 References...........................................................97


3

Preface
This lab manual is compiled for the purpose of developing object-oriented programming (OOP) skills using C++ for 1st year IIUM engineering students. The emphasis of this lab manual is to implement OOP paradigm by helping the students from all programming levels and experiences to solve any engineering-related problems and particularly using computer as a helping hand. This lab manual is aimed at making the students appreciating the theory that they have grasped in Object Oriented Programming for Engineers (ECE 1211) subject. With many suggestions and correction with respect to the first edition, we believe that our humble work deserves criticism and feedback from fellow academicians who have concern with OOP as well our beloved students to improve it for the benefit of all parties involved and ultimately to gain the pleasure of Allah SWT. Nevertheless, the students should bear in mind that independency and willing to exhaustively search for knowledge are two main concepts being employed in university education. Therefore, it is highly hoped that the students will do their own homework and more research (particularly own reading and practice) as to understand both theory and lab components.
Yahya related to me from Malik that he heard that Luqman al-Hakim made his will and counselled his son, saying, "My son! Sit with the learned men and keep close to them. Allah gives life to the hearts with the light of wisdom as Allah gives life to the dead earth with the abundant rain of the sky." Translation of Malik's Muwatta, Book 59: Number 59.1.1 Anas b. Malik reported Allah's Messenger (may peace be upon him) as saying: It is from the conditions of the Last Hour that knowledge would be taken away and ignorance would prevail (upon the world), the liquor would be drunk, and adultery would become rampant. Translation of Sahih Muslim, Book 34: Number 6451 Tell me and I'll forget; show me and I may remember; involve me and I'll understand. Chinese proverb
4

Being ignorant is not so much a shame, as being unwilling to learn. Benjamin Franklin

Developed by: Instructors


I never teach my pupils; I only attempt to provide the conditions in which they can learn Albert Einstein

General Guidelines and Rules


[A]:Guidelines
1. Students must read the lab module and make necessary preparation for

each session PRIOR TO coming to the lab. 2. Each lab session will last for approximately three hours, which is divided into the following time slots: Item Time Tutorial/Demonstration 80 minutes Instructor will give a brief demonstration during the allocated time and students will be given some hands-on exercises. Hence the students are expected to fully utilize this time to enquire the instructor/tutors regarding the subject matter. Lab assignment

Students must:: o Answer all the given questions o Report to the lab instructor and demonstrator to submit the answers before the lab ends No take-home assignment will be allowed. Solutions will ONLY be given after the module is covered by all groups.

90 minutes

3. Referring to the course outline at page 8, 50% will be allocated for lab

assignment and a lab test will solely contribute to the other 50%. Hence, for the assignment component, you will need to go through all 6 modules which are listed in the following Table 1. Each module will be covered within 2 weeks for all groups. Lab No. 1 2 3 4 5 Items Introduction to OOP lab Pointers, reference, array, string class and functions Classes and data abstraction Operator overloading Inheritance Week involved 1-2 3-4 5-6 7-8 9-10

Polymorphism Lab test


Table 1: Modules involved for OOP Lab

11-12 13/14

4. Grading policy for each module:

Item

1 2

Quiz Assignmen t Total

: : :

Weig ht 15% 35% 50%

[B]:Rules
All students are bound to adhere to the following rules. Failure of complying with any rules will be penalized accordingly. 1. Students must be in the lab before the lab activities started. No late coming is tolerated without prior consent from the respective lecturer. Failure to do so may eliminate your mark for that particular lab session. 2. During lab session any form of portable data storage and retrieval devices is prohibited. If found, then we reserve the right to confiscate the item and devoid your mark for that particular lab session. Collection of the confiscated item(s) requires approval from Deputy Dean of Academic Affairs. 3. Duplicated lab assignment: the source and duplicate will be considered void. 4. Submission procedure: a) Create a folder in the D: \ drive of your workstation. Name the folder with your ID number and your name. Example: 04xxxxxx Muhammad Ali b) Save all your answers and source codes inside the folder. Name the files according to the question, example: question1.cpp/question1.txt. c) Report your completed lab assignment to the instructor/demonstrator for inspection and assessment.

[A]:Special Instruction Before Each Lab Session


1. Create 2 folders in the D: \ drive: a. 1 folder for lab exercise and hand-on experience: Name the folder with your ID number and your name with

(demo). Example: 04xxxxxx Muhammad Ali (demo) b. 1 folder for submission (refer to Section B) 2. This lab is aimed to apply the theories that you have learnt in Object Oriented Programming in C++, not intended to teach you everything about C++. Hence, you need to do your own homework. 3. Lab module is designed as a guideline, not a comprehensive set of notes
8

and exercises. Read your theory notes and books pertaining to the topics to be covered (Refer to Objective section in each of the lab module).

[B]:How to get lab manual


1. You can obtain the lab manual in 2 ways:

a. From the selected lab representatives b. From website: http://staff.iiu.edu.my/hadibahmr/ 2. Please get the materials ready before coming to the lab.

10

Course Outline
Kulliyyah Department Programme Course Title Course Code Status Level Credit Hours Contact Hours Prerequisites Corequisites Teaching Methodolog y Method of Evaluation Engineering Electrical and Computer Engineering All Programmes Engineering Lab-II ECE 1201 Core 1 1 3

ECE 1211, ECE 1231 Laboratory Assignments/ reports Tests 50% TOTAL 100% Siti Nuraini and Malik Arman Semester I, 2007/2008 1. To expose student to use C++ as object oriented programming language as opposed to procedural programming language. 2. To develop ability of using OOP to solve simple engineering problems. 3. To prepare students for proper use of lab equipment and elementary electronic components in the design and analysis of electric systems. 4. To introduce experiments involving electronic circuits with Op-Amps, diodes, transistors and JFETs 50%

Instructor(s) Semester Offered Course Objectives

Learning Outcome

After completion of this course the students will be able to:


1. Develop, debug and test object-oriented programs

using C++ programming language.

11

2. Demonstrate

3. 4. 5. 6.

the use of inheritance, operator overloading and polymorphisms in programs. Analyze electronic circuits with experiments. Analyze electronic circuits with computer simulation programs (SPICE). Describe an experimental procedure involving circuits with active elements. Interpret experimental measurements involving electronic circuits with Op-Amps, diodes, transistors and JFETs.

Course Synopsis

Code development using C++ for engineering applications; Practical application of inheritance, overloading and polymorphisms using C++. Experiments on electronic circuits, circuit design techniques, computer assisted analysis, active devices characteristics, rectification, biasing techniques and amplifications. W / eeks 1 Reading Assignment Introduction to object oriented Required 1 programming lab 2 Introduction to electronics lab Required 2 3 Pointers and References Required 1 4 Linear OPAMP Circuits Required 2 5 Classes and Data Abstraction Required 1 6 Diode Characteristics and Wave Required 2 Rectifier 7 Operator Overloading Required 1 8 Zener Diode and Clipping Circuits Required 2 9 Inheritance Required 1 10 BJT Characteristics and Common- Required 2 Emitter Transistor Amplifier 11 Polymorphism Required 1 12 JFET Characteristics and Required 2 Common-Source Transistor Amplifier 13 Lab Test (OOP) Required 1 14 Lab Test (Electronics) Required 2 Required: 1. Laboratory Manuals on Object Oriented Topics

Course Outlines Contents

Reference

12

Proposed Start Date (Semester) Batch of 2005 intake onwards Students to be Affected

Programming 2. Electronics Laboratory Manual Recommended: 1. Harvey M. Deitel and Paul J. Deitel (2004), Simply C++ An Application Driven Tutorial Approach, Prentice Hall 2. Goran Svenk (2002), Object-oriented Programming using C++ for Engineering and Technology, Thomson Delmar Learning 3. Timothy B. DOrazio (2004), Programming in C++: Lessons and Applications, Mc Graw Hill. 4. Hambley, A.R., (2000), Electronics, Prentice-Hall. Semester 1, 2005/06

13

ECE 1201: Object Oriented Programming module

Chapter [1]: Introduction to OOP Lab


1.1Objective
To expose the students with Microsoft Visual C++ Integrated

Development Environment (IDE) To let the student experience coding, compiling and debugging a simple C++ program

1.2Introduction
Programming language which serves as the intelligent of any computer systems has evolved tremendously since it was first developed. Currently, in most electronic devices ranging from mobile handset to washing machine even to cars have computer embedded system and thus requires some form of programming language to govern the operation of those devices. C++ is one of the high-level language that is developed by Bjarne Stroustrup (his personal website: http://www.research.att.com/~bs/homepage.html), of which is actually C is a subset of C++. It is developed on basis of enabling object-oriented programming, where you will learn and apply its concept in this subject.

1.3Working environment
We will use Microsoft Visual C++ Integrated Development Environment (IDE). The environment has the capability of editing, debugging, compiling and executing C and C++ programs. In the following sections, we will have a rapid tour in creating, compiling, performing debug and finally executing our programs or projects. Please explore the Help option yourself in getting used to this compiler. 1.3.1 A Basic C++ Program From time to time, you will get used to the syntax that is being employed by C++. As long as you are familiar with C language, it will provide you good start in understanding the syntax of C++. Observe the following example:
1 2 3
4

#include <iostream> using namespace std; int main() { //print out Welcome to OOP for Engineers to screen
14

ECE 1201: Object Oriented Programming module 5 6

cout<<"Welcome to OOP for Engineers"<<endl; //to hold the execution window system("pause"); return 0; }

7
8

We will try to run this program shortly in Visual-C++.

15

ECE 1201: Object Oriented Programming module

1.3.2 Creating New Source File (Single source program) You can either create a single source file, or a project. The selection for either one will depend on your approach of solving problem. Now, we will demonstrate how to create a single source file. When you select New from the File option, a dialog box will be opened for you (Fig 1.1). You will choose the Files option and from there, click to C++ Source File. Give a file name and save your file into your own intended directory. You will write your source codes at the editor window given for you (Fig 1.2). .

Fig. 1.1 Creating new C++ source file

16

ECE 1201: Object Oriented Programming module

Fig. 1.2 Editor window

17

ECE 1201: Object Oriented Programming module

In saving your file, mind you that you need to follow the instructions as given in the Submission Procedure section as given in the General Guidelines and Rules. Compiling your program is made easy in Visual C++. Fig 1.3 shows you which button to click or else, you can choose the option: Build->Compile SourceFileName.cpp. Then you will need to perform some linking to all associated files and then an executable file of your source code will be created. This is done by choosing Build->Build SourceFileName.exe (Fig. 1.4). Upon the successful completion, you can execute the file.
Click here!

Fig. 1.3 Compiling the source file

18

ECE 1201: Object Oriented Programming module Click here!

Fig. 1.4 Creating an executable file 1.3.3 Creating Project As we proceed further in this subject, we will need to create a project that consists of multiple files, especially when we are creating our own userdefined data type (meaning creating classes). One application might have more than 1 file, lets say it comprises of some header files and source files. You can either: 1. Create the project first, then later you will create the header/source files and add to the project 2. Create the required files prior to creating the project When you select New from the File option, a dialog box will be opened for you (Fig 1.1). You will choose the Projects option and from there, choose Win32 Console Application. In this subject, most of the time, we will be creating console application where you will have your output in MS-Dos Window. Give a name to the project name and choose a directory to save your project. It is much easier if all files and project are in one folder.

19

ECE 1201: Object Oriented Programming module

Choose this!

Fig. 1.5 (a) Creating new project Then just click Finish at the next dialog box that pops up Fig 1.5 (b). Finally, click OK at the next popped-up dialog box (Fig 1.5 (c)).

Fig. 1.5 (b) Creating new project (contd)

20

ECE 1201: Object Oriented Programming module

Fig. 1.5 (c) Creating new project (contd)

21

ECE 1201: Object Oriented Programming module

Provided you have created the header files and source files individually, you will add the associated files to this project. At the left pane of your window, you will see ClassView and FileView. Click to the FileView. Right click to the name of your project and choose Add Files to Project (Fig. 1.6). Locate the directory from which you are going to include the associated files to your application. In creating an executable version of your project, you will choose Build->Build projectname.exe.

Choose this!

Fig. 1.6 Adding files to your project

22

ECE 1201: Object Oriented Programming module

1.4Discussion on the basic of C++ Program


1 2 3 4 5 6 7 8 9 10 11 #include <iostream> using namespace std; int main() { char course_code[10]; //print out Welcome to OOP for Engineers to screen cout<<"Welcome to OOP for Engineers"<<endl; cout<<"Input the course code for this lab:"<<endl; cin>>course_code; cout<<"The course code for this lab is:"<<course_code<<endl; return 0; } 12

Line No.
1 2

Code

Explanation Causes C++ preprocessor to take code existing in iostream file A part of the program in which certain names are recognized; outside of the namespace they are unknown, hence for this purpose, cout is contained inside std namespace. for Single line commenting
for

#include <iostream> using namespace std;

6 7

//print out Engineers cout<<"Welcome Engineers"<<..

Welcome to

to

OOP

OOP

Print out "Welcome to OOP for Engineers" string, similar to


printf()

7 11

..>>endl; cin>>course_code;

Printing single endline Input from user, similar to scanf()

12

.. lab is:"<<course_code<<endl;

Observe how values of variable is printed

1.5Types of Errors
In writing programs, you will come across with some frightening moments when you cannot run your program successfully. But dont be afraid! When you know the difference type of error, then you are able to handle your fear, detect the error and provide correct code for it. Mind you that you should regard writing program is just like writing an essay. Any programming language has its own grammar, specifications and regulations
23

ECE 1201: Object Oriented Programming module

as similar to what you have known in learning any other spoken language. Hence, the syntax of a programming language will detail the rules for creating a proper program in that language.

24

ECE 1201: Object Oriented Programming module

There are basically 2 types of error: 1. Syntax/compilation/compile-time error Meaning: Error that occurs when code statements VIOLATE the grammatical rules of the programming language Example: To omit semi colon at the end of a C++ statement Consequence: Error message will be displayed and the program cannot be run as long as these errors are not corrected 2. Logic/ execution/ run-time error Meaning + Consequence: Error that does not prevent your program from compiling successfully but it does not give the desired results during its execution Example: Error in your algorithm, any mathematical expression

1.6Built-in Data Types


We assume at this point, you are familiar with built-in data types such as int, double, float, char etc. It is also better that you know the size of each data type. In C++, we also have another data type which is bool type. bool will only have two possibilities, true or false. True will be represented as 1 and false will be represented as 0. This following example shows how to use this bool variable.
1 2 3 4 5 6 7 8 #include <iostream> using namespace std; int main() { bool isHot=1;//putting this as yes as default cout<<"Is today hot? 0 for no and 1 for yes"<<endl; cin>>isHot; if(isHot) {cout<<"Today is hot! Drink more water!"<<endl; else {cout<<"Today is cold! Wear thicker clothes!"<<endl;} return 0; } }

9
10

11 12

25

ECE 1201: Object Oriented Programming module

1.7Exercises
Here are some exercises to make the students familiar to the Visual C++ IDE. Follow the submission procedure. 1.7.1 Write codes Write a program that displays the squares, cubes and fourth powers of the numbers 1 through 5. Save the file in your directory as question1.cpp. 1.7.2 Debugging Find errors in these lines of codes. Locate them and give the corrections. Provide your answers in question.txt.
1 2 3 4
5 6 7 8

#include <iostream> using namespace std; int main() { int number1=0,number2=8, value(0); value=number1+number2 cout>>number1<<"+"<<number2<<"="<<value<<endl; return 0; }

26

ECE 1201: Object Oriented Programming module

Chapter [2]: Pointers, reference, array, string class and functions


2.1 Objective
To enhance the understanding of the students about the topics

pertaining to arrays, pointers, reference, string and functions

2.2 Pointer
Basic format for declaring a pointer:
data_type* pointer_name;

During initialization, you can either: Initialize to 0 or NULL, means pointing to nothing Assign to an address of a variable of same type

2.3 Reference
Reference is considered as another name for a variable.
int num(5); int& number=num;

However, if you attempt to reassign a previously declared reference to be an alias to another variable, it will cause a logic error. Example for such a case:
int num(5); int& number=num; int num3=&number;

2.4 Differences between Pointers and References


Restrictions Referenc e It reserves a space in the memory to store No an address that it points to or reference It has to be initialized when it is declared Yes It can be initialized at any time No Once it is initialized, it can be changed to No point to another variable of the same type It has to be dereferenced to get to a value it No points to It can be a NULL pointer/reference No It can point to another reference/pointer No An array of references/pointers can be No Pointe r Yes No Yes Yes Yes Yes Yes Yes

27

ECE 1201: Object Oriented Programming module

created Table 1: Differences between pointer and reference

28

ECE 1201: Object Oriented Programming module

2.5 Static VS Dynamic Memory Allocation


Engineering problems normally require large arrays to store data for some applications. For system of limited memory, having to specify the size of all arrays to be used and allocating the enough memory space for them prior to the program execution could lead to insufficient memory to run the program. Hence, dynamic memory allocation is a way to preventing such a problem to be occurred. In other words, whenever you need the variables, you will create them and you can free the memory at any time in your program whenever you think you dont need them anymore. In C, you use malloc() and free() for such a purpose, but for C++, you will use new and delete operators. Table below summarizes the differences between static and dynamic memory allocation. Static Dynamic Memory space is being allocated Memory space is being allocated during compilation time during run time The amount of allocated memory is The amount of memory is allocated fixed and reserved according to what is needed during execution The memory cannot be released until The memory can be released the program terminates anytime we want, it wont erase the pointer, just the memory space that it is being allocated to Have the possibility of failure in More flexible in this sense, where executing a program when it is memory is only allocated when it is lacking of enough memory needed Example of creating a static pointer: Example of creating a dynamic pointer:
int num(4); int* numPtr=&num; int* numPtr=new int(4);

A region of memory called heap is used for this purpose; a pool of free memory locations that are not being used by any program

Table 2: Differences between static and dynamic memory allocation In using dynamic memory allocation, memory leak problem might occur that can cause memory resource problem. It occurs when you fail to return the memory to the free store when it is no longer in used. Have a look at the example given below:
1 2 3 4 float* ptr=new float; *ptr=7.9; ptr=new float; *ptr=5.1;
29

ECE 1201: Object Oriented Programming module

For this example, in line 1 and 2, you have allocated memory space of type float with value of 7.9 to ptr. Thus ptr holds the address of this block of memory. But without releasing the memory, you reallocate another space of type float with value of 5.1 (as seen in line 3 and 4). The first memory block is not deleted, however the address is lost since ptr now contains the address of the second block. Hence, the program will not be able to use the first block eventhough it still occupies some memory space. Hence, the solution to this problem is to always free the memory that it has been allocated (by using delete operator) before you need to allocate new value to the pointer.

2.6 Arrays
Arrays can be of 1-D or multi dimensional type. Declaration of an array can be done as follow:
data_type arrayName[array_size]

Examples: char name[]={object oriented programming}; int value[5]={1,2,3,4,5}; float number[6]; Some issues regarding arrays: 1. You can either initialize the values for your array elements in the initializer list for the array or perhaps later in your program. 2. If you dont specify the size for the array and only provide the initializer list, its OK. But neglecting to specify any size when you dont give the initializer list will cause error. With related to topic 2.5, you can create dynamically allocated array. The size is depending on how many values needed to be stored during runtime. It can be specified by specifying an integer variable, an integer constant, or an expression. Format of creating and destroy a dynamic array:
data_type pointer_name; pointer_name=new data_type[size]; delete[] pointer_name;

Have a look at this example, which asks the user to input the size of the array:
1 2 3 4 #include <iostream> #include <iomanip> using namespace std; int main() { int *ptr, n;

30

ECE 1201: Object Oriented Programming module 6 7 8 9 10 11 12 13 14

cout<<"Specify the size of an array to be created.."<<endl; cin>>n; ptr=new int[n]; if(!ptr) { { cerr<<"Memory allocation error!"; exit(1); } for(int i=0;i<n;i++) ptr[i]=(i+1)*2; cout<<setw(4)<<ptr[i]; } cout<<endl; delete[] ptr; return 0; }

31

ECE 1201: Object Oriented Programming module

Another example below is about creating a 2-D dynamic array that also prompts for user input.
1 2 3 4 5
6

#include <iostream> #include <iomanip> using namespace std; void memError() { cerr<<"Memory allocation error!"; exit(1);} int main() { int rows,columns,i,j; int** pointer; cout<<"Enter a number for rows: "; cin>>rows; cout<<"Enter a number for columns: "; cin>>columns; pointer=new int*[rows]; if(!pointer) memError(); for(i=0;i<rows;i++) { pointer[i]=new int[columns]; if(!pointer) memError(); } cout<<endl<<"***Multiplication Table***"<<endl; for(i=0;i<rows;i++) { for(j=0;j<columns;j++) { pointer[i][j]=(i+1)*(j+1); cout<<setw(5)<<pointer[i][j]; } cout<<endl; } for(i=0;i<rows;i++) delete[] pointer[i]; return 0;
32

7 8
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

ECE 1201: Object Oriented Programming module

37

33

ECE 1201: Object Oriented Programming module

2.7 String Class


string is another data type supported by standard C++. It eases the

user in many ways. One of its advantages is that user need not to worry about creating an array of right size to hold string variables/values. The string class assumes all the responsibility for memory management. In order to use it, you must include <string> header file. Try to run these codes out! Can you initially guess its output?
1 2 3 4 5
6 7 8 9 10 11 12 13 14 15 16 17

#include <iostream> #include <string> using namespace std; int main() { string s1("Man"); string s2="Beast"; string s3; s3=s1; cout<<"s3="<<s3<<endl; s3="Neither "+s1+" nor "; s3+=s2; cout<<"s3="<<s3<<endl; cout<<s1<<" nor "<<s2<<endl; s1.swap(s2); cout<<s1<<" nor "<<s2<<endl; return 0;}

With this string data type, you can use some operators such as =, += and +. Observe how string variables or objects are created and initialized in line 6, 7 and 8. Line 15 is calling swap() function from object/variable s1, which swapping the values between s1 and s2. You will understand this when you have covered Lab 3! Another convenience that string class provides is during input/output. Observe and run these lines of codes:
1 2 3 4
5 6 7 8

#include <iostream> #include <string> using namespace std; int main() { string full_name, nickname, address; string greeting("Hello, "); cout<<"Enter your full name: "; getline(cin, full_name);
34

ECE 1201: Object Oriented Programming module 9 10 11

cout<<"Your full name is "<<full_name<<endl; cout<<"Enter your nickname: "; cin>>nickname; greeting+=nickname; cout<<greeting<<endl; cout<<"Enter your address in separate lines"<<endl; cout<<"Terminate with '$'"<<endl; getline(cin,address,'$'); cout<<"Your address is: "<<address<<endl; system("pause"); return 0; }

12 13 14 15 16 17 18 19 20

This example reads the users name, which presumably contains blanks, using getline(). The 1st argument is the stream object from which the input will come and 2nd object is the string object where the text will be placed. Line 16 has 3 arguments, where the 3 rd one specifies the character to be used to terminate the input. In this case, we use $ to be inserted by user before ENTER is pressed. This 3rd argument is called delimiter. If no 3rd argument is supplied, by default, the delimiter will be \n . Well, this class has a lot of member functions that you can utilize. You can refer to any online documentations or reference books that further explain about the member function.

2.8 Functions
Basic format of a function prototype:
return_type function_name(argument_list)

Similar to the concept of a black box, function can be treated like a black box where you give some input to that box and request it to perform something in order to obtain the desired output. Hence, as the creator of the function, one should be careful of what you are creating. Avoid from making careless mistakes in providing the return and the arguments lists. Common mistakes done by students that can cause syntax and execution errors are: 1. Not passing the correct values for the parameter list. For example: when a function requires a pointer as argument, then you have to place & operator before the variable name, which means you are

35

ECE 1201: Object Oriented Programming module

passing the address of the variable in calling the function. So be sure of writing the correct syntax for such a purpose. 2. Providing a return type in function header/prototype but not defining it inside function definition. 3. Forgetting to place semicolon at the end of function header/prototype. 4. The function call and function prototype do not match to each other.

36

ECE 1201: Object Oriented Programming module

Some important terminologies These are some terminologies that you normally encounter in class, books or website. By referring to the function given below, Table 3 gives the associated example with its corresponding terminology. Example function: 1 double square (double side) 2 { 3 return side*side; 4 } Terminologies Function header/signature Function prototype Function definition Function call Function parameter Example Line 1
double square (double)

Line 1 to 4
double a=square(5.6); double side

Table 3: Terminologies related to function chapter

37

ECE 1201: Object Oriented Programming module

Chapter [3]: Classes and Data Abstraction


3.1Lab Objectives
To enhance the understanding of student about the underlying concepts of classes To demonstrate the approach to build classes and create object

3.2Introduction
You can view a class as your own customized struct that encapsulates data and function as well. When we encapsulate data and function in one entity, most of the time, the function would not have to take trouble to ask for some data to be included in its argument list, but will still need to if it is required. So it depends on the functionality of the function that youre designing for the class! You will understand why when you create your first class! Format of a class definition:
class your_class_name { member_access_specifier: data members; member_access_specifier: member_functions(); };

When you use cin and cout to perform I/O, you have actually created objects from istream and ostream respectively that has been defined in iostream header file! And also, when you create and use an object of a class in any application, your application is known as a client/user of that class! In contrast to what you have done in Computing Systems and Programming subject, it is about procedural programming where it concerns more on writing functions. However, for this subject, OOP will solve any problem statement based on object oriented programming paradigm, where it concerns on creating objects and deriving classes.

38

ECE 1201: Object Oriented Programming module

Class
Public member function

Client

Private data members Private member functions

Fig 1: Class encapsulates data members as well as member functions. Public member members acts as interface between class and user/client of that class, providing some communication between these two entities by enabling the user to retrieve and modify the private data members

39

ECE 1201: Object Oriented Programming module

3.3Example of A Problem Statement


A bank wants you to create an application that will allow its teller to view client information. The interface is created for you as shown below (Fig 2); you need to implement the Client class which stores the data. Once your application is complete, the bank manager should be able to enter an account number to view corresponding clients information. The information is stored in four arrays containing first names, last names, account numbers and account balances. When the user enters the sentinel value, -1, the application should exit.

Fig 2: Example of the execution window

3.4Lets Build Class Together!


3.4.1 In a single source file As for a start, you will create a class in a single source file along with your main() function. In a single source file, class is defined before the main() function, before you can use it to create objects. Just as you define your functions before you call it. Execute these codes:
1 2 3 #include <iostream> using namespace std; class NewClass { private: int data1; public: //function to initialize data void setData(int d){ data1=d; //function to return data int getData(){ return data1; }

4 5 6 7 8 9 10

11 }; 12 int main() 13 {

14

NewClass n;

40

ECE 1201: Object Oriented Programming module

15
16 }

return 0;

Fig 3: Defining class and main() in one file

41

ECE 1201: Object Oriented Programming module

3.4.1.1Experimenting with member functions a) Observe the output of the program. b) Try to call function getData() in main() function with this line of code:
cout<<"The data in your object is: "<<getData()<<endl;

What do you get? What is the way to call a member function? Do we need to pass any arguments in such a function? Why? c) Now, try to call setData() function. 3.4.1.2Experimenting with data members a) In the NewClass class that you are working on now, you have 1 private data member of type integer. Try to access your data from main() function by writing this line of code:
cout<<"The data in your object is: "<<n.data1<<endl;

What do you get? And why?


b) Create a data member, data2, in public section of type int. c) Make an attempt to access data2 by repeating the same line as given in

a) but change the name of data. Would you be able to run the code? Why? d) Something to think about: What is the reason of us making our data as private and our member function as public? e) Create a print() function that can print out the value of your data members. Example of an output:
data1=9, data2=8

3.4.2 In a multiple files One of the fundamental principles of good software design is to separate a class interface from its implementation. This concept is called separation. What do we mean by this? A class interface consists of member function prototypes, which name the behaviours of the class and for each provide return types and a list of parameter types. Meanwhile the implementation consists of the code that executes when a member function is invoked/called. One of the way of implementing separation in OOP is to separate the function definition into a .cpp source file. Hence, class definition will be included inside a header file that you will create and the function definitions are included in another source file (.cpp). Since you are dealing with multiple files now, you need to group the files into 1 project that serves the solution for any programming problem given to you! Remember how to create
42

ECE 1201: Object Oriented Programming module

project from your Lab 1? From the example of NewClass that we have used earlier, we will create our first header file! 3.4.2.1Creating class definition in a header file a) Create a project with the name MyFirstProject. b) Create a header file named NewClass.h and include it in this project. c) Amend these lines of codes to the class definition.
1 2 3 4
5 6 7 8

#ifndef NEWCLASS_H #define NEWCLASS_H class NewClass { private:

int data1; public: void setData(int); int getData(); void print(); //function to initialize data //function to return data //function to print data

9 10 }; 11 #endif

Fig 4: Defining class definition in a header file d) Take note that NEWCLASS_H can be of any name, but to make things easier,

it is better to follow the name of header file. Line 1, 2 and 11 are preprocessor directives that prevent including the file NewClass.h more than once. This is to ensure that if such a header file of the same name has been defined previously by others, the code between line 2 and 11 are ignored. Such a way will avoid similar and duplicating codes done by you and any other person. 3.4.2.2Defining your member function in a .cpp file a) Add another file to the MyFirstProject folder. Name this file as NewClass.cpp. b) In this file, you will give the definitions for the member function of newclass. Include these lines of codes into the source file youve created.
1 #include <iostream> 2 using namespace std; 3 #include "NewClass.h" 4

43

ECE 1201: Object Oriented Programming module

5 void NewClass::setData(int d) { 6 int NewClass::getData(){ 7 void NewClass::print(){

data1=d;

return data1; } cout<<"Data1="<<data1<<endl;}

Fig 5: Member function definition in NewClass.cpp c) Take note that when you define member function outside the class

definition, you NEED to AMEND class name + scope resolution operator BEFORE the member function name, for example in this case, NewClass::. This will tie the member name to the class name to uniquely identify the functions of a particular class. d) Even though these functions are defined outside class, they are still within that class scope.
e) You might also observe the using of angle brackets, <> and quotes sign,

, in including header files. By putting your header file inside , it will tell the pre-processor that the header file is probably not within the library of standard header files, since you might save your work in other folder. Hence, the pre-processor will search your header file somewhere on the disk storage (It will do the work, not you! But you only provide the instruction for it). 3.4.2.3Creating a driver program a) To use your class and instantiate objects from it, you need to provide the main() function. Hence this will also be in separate .cpp file. Create another .cpp file with the name main.cpp b) From the main() function as shown in Fig 6, amend the necessary line of codes in your source file.
1 2 3 4 5 6 7 8 #include <iostream> using namespace std; #include "NewClass.h" int main() { NewClass n; return 0; }

Fig 4: Main driver program

44

ECE 1201: Object Oriented Programming module

3.4.2.4Run your project a) Save your files and project. Try to execute them. b) Try to call the setData(), getData() and print() functions from the main(). You might refer to what you have done in 3.4.1.1 and 3.4.1.2. 3.4.2.5Experimenting with constructors and destructors a) Constructor is a member function that is automatically called when we create an object, while destructor is automatically called when the object is out of scope. b) Constructor is used to initialize the data members according to the desired value. c) In the NewClass example, previously we called the setData() if we want to give some value to our data member. This function is called after the instantiation of an object.
d) Referring to the NewClass class definition, you have not yet provided

both constructor and destructor. In this case, the compiler will automatically provide default constructor for you. Hence during the instantiation of the object, the data member will be initialized to any value. e) Can you call the setData() function to get the value of your data member? Try this out!

45

ECE 1201: Object Oriented Programming module f) In order to ensure that the data members will be properly initialized, one

will provide explicitly inside class definition and define it in a separate .cpp file alongwith other function definitions (as demonstrated previously). There are 3 types of constructor: a. Default constructor This type of constructor does not have any arguments inside its parenthesis. Is called when creating objects without passing any arguments
NewClass N;

b. Constructor This type of constructor accepts arguments inside its parenthesis Is called when creating objects without passing any arguments
NewClass N(5);

c. Copy constructor (will be ignored for this lab) This constructor is called when: 1. Passing object as an argument to a function
void foo(NewClass n);

2. Return object from a function


NewClass foo();

3. Initializing an object with another object in a declaration statement


NewClass n2; NewClass n1(n2); NewClass n3=n2; //call default constructor //call copy constructor //call copy constructor

g) Provide these codes in the NewClass class definition to visualise how

constructor and destructor should be written. Follow the concept of separation accordingly; i.e. write the function prototype inside the class definition (in a header file .h) and provide the function definition inside the separate member function definition source file (.cpp): a. Default constructor
NewClass() { data1=0; cout<< Default constructor is called<<endl; }

b. Constructor with arguments


NewClass(int d)

46

ECE 1201: Object Oriented Programming module

data1=d; cout<< Constructor is called<<endl; }

c. Destructor
~NewClass() { cout<< Destructor is called; }

47

ECE 1201: Object Oriented Programming module h) In main() function, instantiate some objects with the following codes.

Observe the output.


NewClass obj1(4); NewClass obj2;

i)

Constructor with argument that you have written can also accept default arguments, which will actually perform like a default constructor. Have a look at this example:
NewClass(int d=0) { data1=d; cout<< Constructor is called<<endl; }

j)

By providing many definitions for constructor, you are actually implementing function overloading; i.e. functions of same name but different parameters (not return type) and function definition.

3.5Exercise
Remember the problem statement given in 3.3? You are given with all the associated files. Now we will have to amend the codes in Client.h and Client.cpp so that the main driver will work! Prior to that, assume: The program has pre-defined records kept by the bank. Data stored in the driver program: This is just a simple interface where more enhancements could be made. Account First Name Last Name Balance Number Account 1234652 John Blue 1000.78 1234666 Sarah White 2056.24 1234678 Jack Red 978.65 1234681 Adam Brown 990.00 1234690 Diane Yellow 432.75 1234770 David Black 780.78 1234787 Kristin Green 4590.63 1234887 Jennifer Orange 7910.11

1. Creating project. Create a project and include all these files; Client.h,

and AccountInformation.cpp. 2. Determining variables/data members for the class. Examine the codes from AccountInformation.cpp, including all the get() function calls that the Client object uses to retrieve information. These function calls can be found in the displayInformation function.
Client.cpp

48

ECE 1201: Object Oriented Programming module 3. Creating the Client header file. Switch to your Client.h file. Define 4

private data members, firstName, lastName, account and balance to represent a first name, a last name, an account number and a balance account. Then declare function prototypes for the default constructor and a constructor that takes two strings, one int and one double argument, as well as the necessary get and set functions. Each data member should have a corresponding get and set function. Note: get() function is to return value of data member, while set() function is to initialize data member to the value of the passed argument 4. Creating the Client source code file. Switch to your Client.cpp file. Define the default constructor to use the set functions to assign 0 to the account number and balance amount, and the empty string to the first name and the last name. Then define the constructor that takes arguments and assign the corresponding parameters to the appropriate data members using the set functions. Defining the get() and set() functions. Each data member should have a corresponding get() and set() function. Save, compile and run the application. Test your application to ensure that it runs correctly by entering values at the account number prompt to display the corresponding account record. Make sure that each account indexed in the accountRecords array can be displayed. Close the application. Close the running application by entering -1 at the applications prompt. Close the Command Prompt window.

5. 6.

7. 8.

3.6Summary

Data member should be grouped in private access specifier and member functions are normally clustered together in public section. Attempting to access private members from outside the class will cause syntax error. Providing a constructor to ensure every object is initialized with meaningful values can help eliminate logic errors.

3.7Common mistakes

Member function and data member are encapsulated in one entity. One advantage here is that member function can access the data member directly! As shown in previous example of NewClass class, the setData() is defined such a way that it receives an argument that will initialize
49

ECE 1201: Object Oriented Programming module

data1:void NewClass::setData(int d) { data1=d; int data1=d; } }

Common mistakes done by students:


void NewClass::setData(int d) {

Did you see the mistake? Theres another data1 declared in the function! In truth, it does not have to be like this since a member function can access data members directly without having to declare it again inside the function body.

50

ECE 1201: Object Oriented Programming module

Forgetting to place class name + scope resolution operator, :: when defining member function outside class definition Forgetting to place semicolon ; at the end of closing brace of a class definition Placing class name + scope resolution operator :: at the wrong place, for example:
NewClass::void setData(int d) { data1=d; }

51

ECE 1201: Object Oriented Programming module

Chapter [4]: Operator Overloading


4.1Objectives
To understand the fundamentals of operator overloading To understand the differences between overloading as member function and non-member friend function

4.2Run them out!


Inside the Lab 4 folder that has been given to you, it consists of header file that defines fraction class, source file that defines the member function for fraction class and driver program that contains main() function. By creating a project file and including all these files into the project, compile and try to execute them. What happens?

4.3Why do we need operator overloading?


Before we proceed further, you ought to know the reason we do operator overloading. Do we really need it? For instance, compare the following syntaxes to perform addition of two objects a and b of a user defined class fraction (assume class fraction has a member function called add() which adds two fraction objects):
1 2 c=a.add(b); c=a+b;

Which one is easier to use, line 1 or 2? If your answer is the first statement, then our discussion ends right here. But, we assume that you are obliged to choose the second one. Only then we can continue our discussion. Operator overloading is needed to make operation with user defined data type, i.e., classes, can be performed concisely. If you do not provide the mechanism of how these operators are going to perform with the objects of our class, you will get this error message again and again.

4.4Operator Function
How to define the behaviour of operators in our class? It is like creating a function that describes its behaviours. In C++, an operator is just one form of function with a special naming convention. As such, it can have return value as well as having some arguments or parameters. Recall the
52

ECE 1201: Object Oriented Programming module

general format of a function prototype:


return_type function_name(type_arg1, type_arg2, )

53

ECE 1201: Object Oriented Programming module

An operator function definition is done similarly, with an exception that an operators function name must take the form of operatorX, where X is the symbol for an operator, e.g. +,-, /, etc. For an instance, to declare multiplication operator *, the function prototype would look like
return_type operator*( type arg1, type arg2)

Lets move on to reviewing function overloading. Function overloading means having more than one function with exactly the same function name and each function has different parameters and different return type. For an instance,
int square ( int ); double square ( double);

are some examples of function overloading. We have two functions with the same function name, square and different type of argument, i.e. int and double. Try the following example:
1 2 3 4 5 6 7 8 9
10 11 12 13 14

//example to demonstrate function overloading: square function #include <iostream> using namespace std; //square function with int argument int square(int s){ return s*s; } //square function with double argument double square(double s){ return s*s; } int main() { cout<<"Calling argument"<<endl; cout<<"Square of 5 = "<<square(5)<<endl<<endl; cout<<"Calling square function with DOUBLE argument"<<endl; cout<<"Square of 6.2 = "<<square(6.2)<<endl<<endl; return 0; } square function with INTEGER

Could you compile it? What did you observe from the execution window? Why did the program compile just fine? How the program knows which function to be called? It is because of the signatures for both functions are different and therefore distinguishable. Thanks to function overloading.
54

ECE 1201: Object Oriented Programming module

Well, try to omit line 7 and see what happens! Most of us have been using the operators such as +, -, *, & etc. and pay little attention about what actually is happening. We can easily add an integer with another integer ( int + int ), or add an integer with a floatingtype number ( int + float ) using the very same operator symbol + without questioning anything. How do they work? Hence, what we can say here is that, operator + has been overloaded to perform on various types of builtin data types. We just use them all these while without having to think of the details of how it works with different built-in data types.

4.5Limitation on operator overloading


Although C++ allows us to overload operators, it also imposes restrictions to ensure that operator overloading serves its purpose to enhance the programming language itself, without compromising the existing entity. The followings are the restrictions: Can not change the original behavior of the operator with built in data types. Can not create new operator Operators =, [], () and -> can only be defined as members of a class and not as global functions The arity or number of operands for an operator may not be changed. For example, addition, +, may not be defined to take other than two arguments regardless of data type. The precedence of the operator is preserved, i.e., does not change, with overloading Operators that can be overloaded:

+ = =

<

* >

/ +=

% -=

^ *= != []

& /= <= ()

| %=

~ ^=

! |

<< >> ++ -new[]

>>= <<= == ->* , -> delete[]

>= && || new delete

Operators that can not be overloaded:

.*

::

:?

sizeof
55

ECE 1201: Object Oriented Programming module

Warning: not to abuse operator overloading such that blurs the way how a particular operator operates normally The (=) assignment operator and the (&) address operator are not needed to be overloaded since both can work automatically with whatever data types. (=) assignment operator creates a bit-by-bit copy of an object while the (&) address operator returns a memory address of the object. The exception comes when we deal with classes containing pointers as members. In this case, the assignment operator needs to be overloaded explicitly.

56

ECE 1201: Object Oriented Programming module

4.6Choice on overloading an operator


There are many ways of performing operator overloading, namely: 1. as member function 2. as non member friend function 3. as non member non friend function Since we have these possibilities, we are actually going to implement function overloading principle here. These possibilities that we have here will determine how many arguments we are giving to the operator function. Another factor that influences the number of arguments is the type of operator, whether it is unary operator or binary operator. Again, the difference is only in the implementation and do not affect at all the usage. Whatever implementation we chose, the usage will be the same. Recall our question on how operator overloading works for built-in data types. How does it work? How several operator functions having exactly the same name do not conflict each other? Yes, the answer is because the C++ library has overloaded the addition operator (operator+) function for relevant data types. When the same operator is called or invoked with different types of operand, the appropriate version of the operator is called. For section 4.6.1 and 4.6.2, we are going to consider this expression, where we want to add two operands, a and b and we want to assign the results to object c. All a, b and c are of type fraction.
c = a + b; [1]

We will consider this case-by-case now, which are:


1. fraction + fraction;
2. fraction + built-in data type;

[2] [3] [4]

3. built-in data type + fraction;

4.6.1 Overload as Member Function Before we move on, do you still remember how we call member function? Lets assume we have an object, object1 of type fraction and we want to call a member function print() through object1. What is the syntax for this?

57

ECE 1201: Object Oriented Programming module

As to start with, add this line of code inside fraction.h:

fraction operator+(const fraction&);

And add these lines of codes in fraction.cpp:


1
2 fraction fraction::operator+(const fraction& c) { fraction temp; temp.numerator=numerator * c.denominator + denominator * c.numerator; temp.denominator=denominator * c.denominator; return temp; }

3 4 5 6
7

Some observations: 1. Why we have fraction as return type? 2. Why we have only one argument and it is fraction type? When we overload + operator as member function, the way we call the operator function is also the same with what we have done before, which is through an object of that class and using dot (.) operator. Hence, what happens when the compiler see expression [1] is that it will call the operator+() function that we have defined through the left object, which is object a.
a.operator+(b);

Next, the return value type will naturally be a Fraction object as well (You have choice whether to return a Fraction object or a reference to Fraction object, though). So, now we have sufficient knowledge on how to declare the prototype function. It will look like
fraction& operator+ (const fraction &);//return a reference

OR
fraction operator+ (const Fraction &); // return a value

4.6.2 Overload as Non-Member Function If we choose to implement it as non-member friend function, the function prototype will look like:
friend fraction operator+( const fraction&, const fraction& );
58

ECE 1201: Object Oriented Programming module

Can you figure out the difference? Yes, now we have the two operands appear as arguments.

59

ECE 1201: Object Oriented Programming module

By omitting what you have done in 4.6.1, add this line of code inside fraction.h:
friend fraction operator+(const fraction&, const fraction&);

Followingly, add these lines of codes in fraction.cpp:


1 2 fraction operator+(const fraction& c, const fraction& d) { fraction temp; temp.numerator=c.numerator * d.denominator + c.denominator * d.numerator; temp.denominator=c.denominator * d.denominator; return temp; }

3 4 5 6
7

The usage of the overloaded function, whether implemented as member function or non-member (friend) function does not have any difference. But take note, that the compiler interprets the same statement slightly differently. When it sees statement:
c=a+b;

it is interpreted as:
c=operator+( a, b );

which means operator+() is called and passes object a and b as arguments. Then, your curious mind may question: what is the motivation for choosing member function over non-member (friend) function or vice versa if thats the only difference. We would agree with you. Before we proceed, inside the main(), please modify the statement c = a + b; with c = b + a; What is your observation? The same result, c=a+b = b+a. It is because the two operands a and b are of the same type. 4.6.3 Some Other Possibilities What we have done in section 4.6.1 and 4.6.2 is only considering fraction + fraction (expression [2]). Now lets consider expression [3], which is to add class fraction object a and an integer variable b ( fraction
60

ECE 1201: Object Oriented Programming module

object + built-in data type variable). Here, we have two objects of different types. The result, c is of type Fraction. c = a + b;

61

ECE 1201: Object Oriented Programming module

Are we able to implement operator+ as either member function or non-member (friend) function. Lets implement it as member function first. By retaining what you have done in 4.6.2, add this line of code inside fraction.h:
fraction operator+(const int&);

Followingly, add these lines of codes in fraction.cpp:


1 2 fraction fraction::operator+(const int& a) { fraction temp; temp.numerator=numerator + denominator * a; temp.denominator=denominator; return temp; }

3 4 5 6
7

Next, amend your main() according to the lines of codes as below:


1 2 int main() { fraction a(1,2),b(1,3),c; int number(7); c=a+number; a.print(); cout<<" + "<<number<<" = "; c.print(); cout<<endl; return 0; }

3 4 5 6 7 8 9

Can you try to implement it as non-member function? (Hint: Refer to 4.6.2) Now, lets see the last possibility which is:
built-in data type + fraction; [4]

62

ECE 1201: Object Oriented Programming module

Can you guess whether we should implement it as member function or nonmember function? Why? 4.6.4 Overload insertion operator, << This section will try to eliminate print() member function that we have earlier by overloading insertion operator, <<, but maintaining the purpose which is to print out the fraction object in this form of output, assume fraction object1(4,5), example of output: 4/5

63

ECE 1201: Object Oriented Programming module

Where do you normally use insertion operator, <<? Assume we have these lines of codes:
cout<< I love programming.. it challenges my thinking capabilities..;

What is the expected output? In dealing with class or user-defined data type, we have to also overload this insertion operator when we want to use it with the objects of our class. Like what we have done before, calling print() function from object a,
a.print();

which prints out the object of a in terms of X/Y, we want to use the following line of code that produces the same output.
cout<<a;

Doesnt it look simpler? Well, some issues that might arise here: 1. In what way can we overload it? As member function or nonmember friend function? 2. What should be the arguments for operator<<() function? 3. What should be the return type? Add this line of code inside fraction.h:
friend ostream& operator<<(ostream&, const fraction&);

Followingly, add these lines of codes in fraction.cpp:


1 2 ostream& operator<<(ostream & out, const fraction & f) { out<<f.numerator<<"/"<<f.denominator; return out; }

3 4
5

Next, amend your main() according to the lines of codes as below:


1 2 int main() { fraction a(1,2),b(1,3),c; int number(7);

3 4

64

ECE 1201: Object Oriented Programming module

5 6 7

c=a+b; cout<<a<<" + "<<b<<" = "<<c<<endl; return 0; }

65

ECE 1201: Object Oriented Programming module

Chapter [5]: Inheritance


5.1Objectives

To understand the fundamentals of inheritance as opposed to composition To develop skills on how to use inheritance to simplify development of new classes To understand some concepts such as overridden function, protected access specifier and the sequence of constructor and destructor calls

5.2

Inheritance vs. composition

Initially, OOP is proposed as a means to increase the efficiency of software developments. One of its benefits is promoting software/program reuse. Once a class is developed reliably, i.e., after went through all sorts of possible verification processes, it can be used everywhere. It can be used right away, without needing to reinvent the wheel.. There are two forms of software reuse in OOP. The first one is composition which is a has a(n) relationship. For instance, we consider a car. A car consists of engine, tires, body, steering wheel, etc. So, we can have A car has an engine. A car has a steering wheel. A car has a body. Note that in the above relationship, the enclosing entity is the car object. It encloses engine, steering wheel and body objects. It is clear from logical relationship that a car is not an engine or a steering wheel. This is clearly shown in Fig. 5.1 that Engine, Body and Steering wheel are part of class Car.
Car Engine Body Steering wheel

Fig. 5.1 Composition; a has a relationship On the other hand, inheritance relationship is also called an is a(n) relationship. For instance, again we consider car as example.
66

ECE 1201: Object Oriented Programming module

A Honda CRV is a car. A Mitsubishi Lancer is also a car. A Kia Sorento is yet another car. From the above example, we have the common denominator/type/class: a car. Honda CRV, Mitsubishi Lancer and Kia Sorento are specifics examples of car.

67

ECE 1201: Object Oriented Programming module

Difference between inheritance and composition: a. Composition does not enhance the existing classes. The enclosing class is just like a client of the existing classes. b. Inheritance enhances the existing classes. It inherits all existing classes (data and function) members and enhances the existing classes by adding new members (data and function). In the upcoming discussion we will make this thing clear through examples. InsyaAllah!
Car

Honda CRV

Mitsubishi Lancer

Kia Sorento

Fig. 5.2 Direct inheritance, implementing is a relationship

5.3Inheritance
Before we proceed, we will define a few terminologies commonly used in inheritance in C++.
Vehicle Truck Truck Direct inheritance with class Vehicle Direct inheritance Bus Bus Indirect inheritance MPV MPV Sedan Sedan Indirect inheritance with respect to class Vehicle

Car Car

Indirect inheritance Indirect inheritance with respect to class Car HondaCivic HondaCivic NissanPresident

Fig. 5.3 Inheritance hierarchy for Vehicles Important terminologies: base class: a class which is inherited from by other classes. E.g., class Vehicle is the base class for all other classes. Class Sedan is base class for classes HondaCivic and class NissanPresident. derived class: a class which inherits from base class(es). E.g., classes Truck, Car and Bus are derived classes from base class Vehicle. direct inheritance: inheritance relationship where the derived class
68

ECE 1201: Object Oriented Programming module

inherit directly from its base class. E.g., class Car and class Vehicle have direct inheritance relationship. indirect inheritance: inheritance relationship where the derived class inherit indirectly from its base class. E.g., class HondaCivic and class Car have indirect inheritance relationship. single inheritance: a derived class inherits from a single base class. E.g., all examples in Fig. 5.3 are single inheritance multiple inheritance: a derived class inherits from more than one base classes. A note on multiple inheritance is that although it is supported by C++ it must be used carefully since it may cause conflict between class members of different base classes. From the example in Fig. 5.3, we can say the following: A HondaCivic is a Sedan. (Direct, single inheritance) A HondaCivic is a Car. (Indirect, single inheritance) A HondaCivic is a Vehicle. (indirect, single inheritance) A deeper look to the above examples will give you a notion that a HondaCivic is a specific/special category of a Sedan. A HondaCivic has all the attributes (data members) and functionalities (member functions) of a Sedan. On top of that, it may have other attributes and functionalities which are not possessed by Sedan in general. Yet, a HondaCivic is a Sedan. 5.3.1 Type of inheritance: private, protected, public There are three types of inheritance, namely private, protected and public inheritances.
Base class member access specifier Type of inheritance public inheritance public in derived class. Can be accessed directly by any non-static member functions, friend functions and nonmember functions. protected inheritance protected in derived class. Can be accessed directly by all non-static member functions and friend functions. protected in derived class. Can be accessed directly by all non-static member functions and friend functions. Hidden in derived class. Can be accessed by non-static member functions and friend functions through public or protected member functions of the base class. private inheritance private in derived class. Can be accessed directly by all non-static member functions and friend functions. private in derived class. Can be accessed directly by all non-static member functions and friend functions. Hidden in derived class. Can be accessed by non-static member functions and friend functions through public or protected member functions of the base class.

Public

protected in derived class. Can be accessed directly by all Protected non-static member functions and friend functions. Hidden in derived class. Can be accessed by non-static member functions and friend functions through public or protected member functions of the base class.

Private

69

ECE 1201: Object Oriented Programming module

Fig. 5.4 Type of inheritance (Taken from Deitels&Deitels) As you can observe from Fig. 5.4, different types of inheritances have different effect on how members of the base class can be accessed from the derived classes. In this lab session we will focus only on public inheritance. This is the most widely used type of inheritance. And it is the only type that realizes is-a relationship.

70

ECE 1201: Object Oriented Programming module

General syntax for single inheritance:


Derived_class_name : type_of_inheritance Base_class_name{};

General syntax for multiple inheritance:


Derived_class_name : type_of_inheritance1 Base_class_name1, type_of_inheritance2 Base_class_name2,{};

How inheritance benefits us? Lets consider the following example. Create two projects. The first project will include point.h, point.cpp and mainPoint.cpp. The 2nd project will include circle.h, circle.cpp and mainCircle.cpp.
//point.h #ifndef POINT_H #define POINT_H #include <iostream> using namespace std; class Point { private: int x; int y; public: Point(int, int); void setPoint(int,int); void print(); }; #endif //point.cpp #include <iostream> using namespace std; #include "point.h" Point::Point(int x, int y):x(x),y(y) { cout<<"Point constructor"<<endl; } }; #endif //circle.cpp #include <iostream> using namespace std; #include "circle.h" Circle::Circle(int d):x(x),y(y) { this->radius=(d>0.0)? d:1.0; x, int y, double //circle.h #ifndef CIRCLE_H #define CIRCLE_H #include <iostream> using namespace std; class Circle { private: int x; int y; double radius; public: Circle(int, int, double); void setPoint(int,int); void setRadius(double); void print();

71

ECE 1201: Object Oriented Programming module

cout<<"Circle constructor"<<endl; } void Point::setPoint(int x,int y) { this->x=x; this->y=y; } void Circle::setPoint(int x,int y) { this->x=x; this->y=y; void Point::print() { cout<<"["<<x<<","<<y<<"]"<<endl ; } } void Circle::print() { cout<<"["<<x<<","<<y<<"]" <<" radius: "<<radius<<endl; //mainPoint.cpp #include <iostream> using namespace std; #include "point.h" int main() { Point point1(-5,5); point1.print(); point1.setPoint(3,2); point1.print(); return 0; } } } //mainCircle.cpp #include <iostream> using namespace std; #include "circle.h" int main() { Circle circle1(4,2,4); circle1.print(); circle1.setPoint(0,0); circle1.setRadius(-1); circle1.print(); return 0; { this->radius=(rad>0.0)? rad:1.0; }

void Circle::setRadius(double rad)

Table 1: Class definitions for class Point and Circle and their respective main drivers By comparing both class definitions with its member functions definition, what do you think? Although both classes work just fine, we note some redundancy of codes here. The redundancy will be enormous and much worse when we consider real world applications.

72

ECE 1201: Object Oriented Programming module

Fig. 5.5 Example of output from Table 1

73

ECE 1201: Object Oriented Programming module

Now, lets see how we can simplify and thus make efficient the class Circle by virtue of inheritance. We want class Circle to be derived from class Point. Make the following changes to circle.h and circle.cpp. Create another project that includes all files: point.h, point.cpp, circle.h, circle.cpp and mainCircle.cpp.
//circle.h #ifndef CIRCLE_H #define CIRCLE_H #include <iostream> using namespace std; #include "point.h" int main() class Circle: public Point { private: double radius; public: Circle(int, int, double); void setRadius(double); void print(); }; #endif //circle.cpp #include <iostream> using namespace std; #include "point.h" #include "circle.h" Circle::Circle(int x, int y, double d):Point(x,y) { this->radius=(d>0.0)? d:1.0; cout<<"Circle constructor"<<endl; void Circle::setRadius(double rad) { this->radius=(rad>0.0)? rad:1.0; } } } return 0; { Circle circle1(4,2,4); circle1.print(); circle1.setPoint(0,0); circle1.setRadius(-1); circle1.print(); //mainCircle.cpp #include <iostream> using namespace std; #include "point.h" #include "circle.h"

void Circle::print()

74

ECE 1201: Object Oriented Programming module

Point::print(); cout<<" radius: "<<radius<<endl; }

Table 2: Class Circle inherits publicly from class Point.

75

ECE 1201: Object Oriented Programming module

Discussion: A sample output from Table 2:

Fig 5.6 Example of output from Table 2 Lets compare the definition for class Circle in Table 1 and Table 2. In Table 2, data members x and y are not explicitly declared as in Table 1. However, these data members can still be used (indirect access through class Point public member functions) by derived class Circle, since both are inherited from base class Point. Next, member function setPoint() is not explicitly declared in Table 2 but it can be called just like we call other public member functions of class Circle as is shown in the main(). Class Members
int x; int y; Circle()

setPoint() print()

Class Circle in Table Class Circle in Table 2 1 Explicitly declared Inherited from base class Point Use member initializer Use/call constructor for list to initialize x and y base class Point to initialize x and y Explicitly declared Inherited from base class Point Explicitly declared Partially use print() declared in base class Point

Table 3: Differences of class Circle declarations: with and without inheritance Finally, we have print() member function which are defined in both class-declarations. In Table 2, print() member function is supposed to be inherited from base class Point. That is, if it is not declared in derived class Circle, print() function from base class Point will be called in main(). However, in this example, member function print() is re-defined in the derived class Circle. Note here that both functions (print() in the base class Point and print() in the derived class Circle) have exactly the same function headers, i.e., same parameter type, order and number. This is called member function overriding (dont be confused with function overloading).
76

ECE 1201: Object Oriented Programming module

Try to comment out member function print() declaration in derived class Circle, recompile and rerun program in Table 2. Did you get something like this?

Fig 5.7 Example of output when omitting the print() from class Circle

77

ECE 1201: Object Oriented Programming module 5.3.2 protected Data Member

Alter the print() as defined in Table 2 with this codes:


void Circle::print() { cout<<"["<<x<<","<<y<<"]" <<" radius: "<<radius<<endl; }

What is the outcome? Remember: private class members are accessible from within class scope (by member functions of the same class) and friend functions. Hence, another member access specifier called protected is provided to enable its members accessible directly from: within the class scope friend functions derived classes friend functions of derived classes

//cylinder.h

Lets modify slightly the declarations of class Point to see the effect of using protected members in base class. 1. Change the access specifier for data member of class Point from private to protected. 2. Compile and execute again! What do you get? Can you see the benefit of using protected data members in the base class from the above example? It reduces the function call overhead through direct access to protected base class members. Now, derive class Cylinder from class Circle with the following class definition. Do not forget to change the access specifier for data member of class Circle from private to protected. Create a new project and include point.h, point.cpp, circle.h, circle.cpp, cylinder.h, cylinder.cpp and mainCylinder.cpp.

#ifndef CYLINDER_H #define CYLINDER_H #include "circle.h" class Cylinder:public Circle { private: double height; public:

78

ECE 1201: Object Oriented Programming module

Cylinder(int,int,double,double); void setHeight(double); void setRadius(double); void print(); #endif //cylinder.cpp #include <iostream> using namespace std; #include "cylinder.h" Cylinder::Cylinder(int x,int y,double r,double h):Circle(x,y,r), height(h) { cout<<"Cylinder constructor"<<endl; } this->height=h; this->radius=r; } } void Cylinder::setHeight(double h){ void Cylinder::setRadius(double r){ void Cylinder::print() { Circle::print(); cout<<"Height: "<<height<<endl; } //mainCylinder.cpp #include <iostream> using namespace std; #include "cylinder.h" int main() { Cylinder tube(1,1,2.5,10); tube.print(); tube.setRadius(-5); tube.print(); return 0; } };

Table 4: Definition for class Cylinder and its associated main driver Did you get such an output? What do you observe here?

79

ECE 1201: Object Oriented Programming module

Fig 5.8 Example of output from Table 4 The important thing here is that protected data member must be used very cautiously. Indeed, it does improve the performance by reducing function call overhead. However, as you can see from the above example, it may compromise the integrity of data via assignment of non-valid values to data.

80

ECE 1201: Object Oriented Programming module

5.3.3 Sequence of Constructor and Destructor Calls You SHOULD observe from Fig. 5.6, 5.7 and 5.8 that constructor calls sequence starts with the constructor of top-most base class to the downmost derived class. The opposite way applies to the destructor calls where it starts from the deriveds version up to bases version. By retaining the recent project that youre working on, add according line of codes to your point.h, point.cpp, circle.h, circle.cpp, cylinder.h and cylinder.cpp, run them and observe the output.
//point.h ~Point(); //circle.h ~Circle(); //cylinder.h ~Cylinder(); //point.cpp Point::~Point() { cout<< Point destructor <<endl; } //circle.cpp Circle::~Circle() { cout<< Circle destructor <<endl; } //cylinder.cpp Cylinder::~Cylinder() { cout<<Cylinder destructor <<endl; }

Table 5: Defining destructor for various classes Did you get such as output?

Fig 5.9 Example of output after including destructors for various classes

81

ECE 1201: Object Oriented Programming module

Chapter [6]: Polymorphism


6.1

Objectives
To learn the difference between inheritance and polymorphism To understand the mechanism of polymorphism through virtual function To understand the concept of an abstract base class

6.2Run them out!


Create a project that includes all the provided files: base.h, base.cpp, derived.h, derived.cpp and main.cpp. Did you get such an output?

Fig 6.1: Example of output from Section 6.2 Add these line of codes into your main() and observe what happens.
derivedPtr=&object1; derivedPtr->print();

Lets analyze! 1) Pointers of each class that point to object of their own class are able to call functions from the pointed object. Example, basePtr (base-class type) points to object1 (base-class type) and calls print() function and same goes to derivedPtr (derived-class type) that is pointing to object2 (derived-class type) 2) Base-class pointer is able to point to its own-class object and object of its derived classes. 3) Derived-class pointer is able to point to its own-class object and requires some type-casting (means to temporarily change its type) if it wants to point to object of its base classes. 4) Consider a situation that has some functions with same signature in some/all classes in that hierarchy. A base-class pointer that
82

ECE 1201: Object Oriented Programming module

points to objects of different classes in that hierarchy and attempts to call such a function will only able to call the base version. BUT, in truth, the pointer wants to call the appropriate version corresponding to the class an object is from. This is what we are going to resolve in this lab!

83

ECE 1201: Object Oriented Programming module

6.3Introduction
This chapter concerns on solving point 4) mentioned in section 6.2, which aims to enable the base-class type pointer to call the correct version of functions based on which object it is currently pointing to. This is actually about dynamic binding, which means the sequence of function calls will be determined during run-time. Considering this example: You have class animal as the base class, and from that you derive class fish, insects, birds, mammals etc. From there, you will derive more classes, lets say from class fish, youll have piranha, salmon etc. Same goes to other classes. For each of the classes, you will create a function move() to simulate the movement of each animal class. BUT, the way fish moves is different from the way a bird moves. Hence, what you have here is just the same BEHAVIOUR/FUNCTION SIGNATURE but different IMPLEMENTATION depending on each animal!
6.4

Static Binding vs. Dynamic Binding

Binding means the actual time when the code for a given function is attached or bound to the function call. Static Binding Dynamic Binding Actual code will be attached during Actual code is attached during run-time/execution time compile time. Implementing function overloading Implementing virtual functions Table 1: Comparison between static binding and dynamic binding
6.5

Implementing Polymorphism

A POLYMORPHIC function is one that has the same name for different classes of the same family, but has different implementations/behaviour for the various classes. In other words, polymorphism means sending the same message (invoke/call member function) to different objects of different classes in a hierarchy. There are 3 pre-requisite before we can apply virtual functions: 1. Having a hierarchy of classes/implementing inheritance 2. Having functions with same signatures in that hierarchy of classes, but each function in each class is having different implementation (function definition) 3. Would like to use base-class pointer that points to objects in that hierarchy
84

ECE 1201: Object Oriented Programming module

To enable polymorphism, the first thing that we need to do is declaring the overridden function as virtual one in the base class declaration. Once it is declared virtual, it is also virtual in the derived classes implicitly. However, it is a good practice to declare the function to be virtual as well in the derived classes.

85

ECE 1201: Object Oriented Programming module

To implement virtual functions, you will just place virtual keyword at the function prototype as shown below:
virtual return_type functionName( argument list );

Can you try to place virtual keyword at the print() function in both base and derived classes that we did earlier? Did you get such an output?

Fig 6.2: Example of output when we implement virtual functions with respect to section 6.2 What we observe is that the same message print() are sent to different classes object through base class pointer, have different effects or give different results. Some points to be raised: Declaring virtual-ness of overridden function in the derived classes declaration improves the clarity of the program. When a function is declared as virtual function in a base class, the compiler knows that the base class implementation might be overridden in a derived class. If the base version is not overridden in a given derived class, then the base implementation is available to the derived class.

6.6Abstract Base Class


Consider vector objects. We can have vector of two dimensions (vector with two elements), three dimensions, four dimensions and so forth. All vectors have the same behaviour, namely know their respective magnitude or distance from the origin. In such case, it will be more convenience if we can create a base class of all that governs general
86

ECE 1201: Object Oriented Programming module

behaviour (common behaviour) of objects of classes in the inheritance hierarchy. However, this base class does not need to provide a specific about the behaviour or the definition of the pertinent member functions. A base class which does not have the implementation of one or more of its virtual member functions is said to be an abstract base class. In other words, an abstract base class is a base class without the definition of one or more of its virtual member functions. It serves as a framework in a hierarchy and the derived classes will be more specific and detailed. Further, a virtual member function which does not have its implementation/definition is called a pure virtual member function. An abstract base class is said to be incomplete missing some of the definition of its virtual member functions and can not be used to instantiate objects. However, it still can be used to instantiate pointer that will be used to send messages to different objects in the inheritance hierarchy to affect polymorphism. Pure virtual member function declaration:
virtual return_type functionName( argument_list ) = 0;

Implementation/defini tion Overriding

Virtual function Yes Optional

member Pure virtual member function No (initialized to =0) Must

Table 2: Comparison between virtual and pure virtual member function Abstract base class Yes Yes Yes No Yes Concrete base class Yes Yes No Yes Yes

Data member Virtual function Pure virtual function Object instantiation Pointer instantiation

Table 3: Comparison between abstract and concrete base classes Create a project that includes all these files.

//record.h

//record.cpp #include <iostream> using namespace std; #include "record.h" #include <string> record::record()

#ifndef RECORD_H #define RECORD_H #include <string> using namespace std; class record

87

ECE 1201: Object Oriented Programming module

protected: string name; public: record(); virtual void getData(); virtual void print()=0; };

{ {

name="";

void record::getData() cout<<"Enter name:"; cin>>name; fflush(stdin); } //student.cpp #include <iostream> using namespace std; #include "record.h" #include "student.h" student::student():record(),studentID(0){} void student::getData() { cout<<"++Entering record for student++"<<endl; record::getData(); cout<<"Enter student ID:"; cin>>studentID; } void student::print() { cout<<"Student's record:"<<endl <<" \ tName:"<<name<<endl <<" \ tStudent ID:" <<studentID<<endl; } //staff.cpp #include <iostream> using namespace std; #include "record.h" #include "staff.h" staff::staff():record(),staffID(0){} void staff::getData() { cout<<"++Entering record"; <<"for staff++"<<endl; record::getData();

#endif //student.h #ifndef STUDENT_H #define STUDENT_H #include <string> using namespace std; class student: public record { private: int studentID; public: student(); virtual void getData(); virtual void print(); }; #endif

//staff.h #ifndef STAFF_H #define STAFF_H #include <string> using namespace std; class staff: public record { private: int staffID; public:

88

ECE 1201: Object Oriented Programming module

staff(); virtual void getData(); virtual void print(); }; #endif } {

cout<<"Enter staff ID:"; cin>>staffID; } void staff::print() cout<<"Staff's record:"<<endl <<" \ tName:"<<name<<endl <<" \ tStaff ID:"<<staffID<<endl;

89

ECE 1201: Object Oriented Programming module

//mainRecord.cpp #include <iostream> using namespace std; #include "record.h" #include "staff.h" #include "student.h" int main() { record* recordPtr; student student1; staff staff1; recordPtr=&student1; recordPtr->getData(); recordPtr->print(); recordPtr=&staff1; recordPtr->getData(); recordPtr->print(); return 0; }

6.7Advantages of Polymorphism
It allows objects to be more independent, though belong to the same

family New classes can be added to the family without changing the existing ones and they will have the basic same structure with/without added extra feature It allows system to evolve over time, meeting the needs of a everchanging application

6.8An example
Study the following example. This program applies the concept of polymorphism and creating an abstract base class named person that serves as a framework of the characteristics and behaviour of the derived classes, student and professor. Two pure virtual functions (Line 18 and 19)
90

ECE 1201: Object Oriented Programming module

are created, namely getData() and isOutstanding().These functions are redefined and overridden in each derived classes based on the characteristics of that class (Line 30 and 41) . In the main driver program, the user is able to choose whether he wants to create a record for student or professor. This is an example of a dynamically memory allocation. Memory is allocated only upon request/need. Since this application created virtual functions, the base-class pointer, persPtr is able to call the corresponding function based on the type of the pointed object.
1 2 3 4 5 6 7 8 9 // virtpers.cpp // virtual functions with person class #include <iostream> #include <istream> #include <string> using namespace std; //////////////////////////////////////////////////////////////// class person { protected: string name; public: void getName() { cout << " Enter name: "; } getline(cin,name); void putName() { cout << "Name is: " << name << endl; } //pure virtual function //pure virtual function virtual void getData()=0; virtual bool isOutstanding()=0; //person class

10 11 12 13 14 15 16 17 18 19
20 };

21 //////////////////////////////////////////////////////////////// 22 class student : public person 23 { //student class

24 25 26 27 28 29

private: float gpa; public: void getData() { person::getName(); cout << " Enter student's GPA: "; cin >> gpa; } //get student data from user //grade point average

91

ECE 1201: Object Oriented Programming module 30


31 }; 32 //////////////////////////////////////////////////////////////// 33 class professor : public person //professor class //number of papers published

bool isOutstanding() { return (gpa > 3.5) ? true : false; }

34 { 35 36

private: int numPubs; public:

92

ECE 1201: Object Oriented Programming module 37 38 39 40 41


false; } 42 }; 43 //////////////////////////////////////////////////////////////// 44 int main() 45 {

void getData() { person::getName(); cout << "

//get professor data from user Enter number of professor's publications: ";

cin >> numPubs; } bool isOutstanding() { return (numPubs > 100) ? true :

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
69 }

person* persPtr[100]; int n = 0; char choice; do {

//array of pointers to persons //number of persons on list

cout << "Enter student or professor (s/p): "; cin>>choice; fflush(stdin); if(choice=='s') persPtr[n] = new student; else persPtr[n] = new professor; persPtr[n++]->getData(); cout << " cin>>choice; fflush(stdin); } while( choice=='y' ); for(int j=0; j<n; j++) { persPtr[j]->putName(); cout << " } //end main() if( persPtr[j]->isOutstanding() ) This person is outstanding"<<endl; //cycle until not 'y' //print names of all //persons, and //say if outstanding // // //put new student in array //put new professor in array //do another person? //get data for person

Enter another (y/n)? ";

68 return 0;

93

ECE 1201: Object Oriented Programming module

Appendix A: C++ Reserved Words


C++ reserves some words for its own use in the libraries. These words have special meaning to the compiler and therefore can not be used as identifiers in a declaration statement. Reserved words are classified into three categories: C++ Keywords asm catch continue dynamic_cast extern goto mutable protected return static_cast throw typename void Alternative Tokens Alternative tokens are the equivalences of operators at the right side of the following list. Token and and_eq bitand bitor compl not not_e or or_eq xor xor_eq Meaning && &= & | ~ ! != || |= ^ ^= union volatile struct true public short switch try unsigned wchar_t default else false if namespace new register signed auto char delete enum float inline bool class do explicit for int operator reinterpret_cast sizeof template typedef using while static this typeid virtual break const double export friend long private case const_cast

94

ECE 1201: Object Oriented Programming module

C++ Library Reserved Names There are a number of identifiers that are already in use in C++ libraries, if incidentally used by the programmer may result in unpredictable behavior of the program. That is, it might generate compiler error, warning, incorrect result/outcome or maybe the program just run well. For example, C++ reserves names beginning with two underscores or a single underscore followed by an uppercase letter and naves beginning with a single underscore for use as global variable. Therefore, avoid creating identifier such as __param or _Param in your program. Another example is identifier sin is already defined in math library. If you want to use, i.e., include, the math library in your program, avoid declaring a function with the same name sin, although the compiler has the capability of distinguishing it through the use of function signature.

95

ECE 1201: Object Oriented Programming module

Appendix B: ASCII Character Set


American Standard Code for Information Interchange (ASCII) is a character set the most widely used at the early development of computers, proposed by ANSI in 1963. It uses an 7-bit word to represent a character so that at maximum 2 7=128 characters can be represented.. ASCII code is the numerical representation of a character such as 'x' or '$' or any action commonly required in simple data interchange. Later on, ASCII code was extended to cater for the need of increasing demand to represent additional characters on the computer. This stem to the Extended ASCII character set consist of 128 characters. Below is the original ASCII character set consisting of 128 characters.

96

ECE 1201: Object Oriented Programming module

References
1. Harvey M. Deitel and Paul J. Deitel (2004), Simply C++ An Application

Driven Tutorial Approach, Prentice Hall 2. Goran Svenk (2002), Object-oriented Programming using C++ for Engineering and Technology, Thomson Delmar Learning 3. Timothy B. DOrazio (2004), Programming in C++: Lessons and Applications, Mc Graw Hill. 4. Stephen Prata (2005), C++ Primer Plus fifth edition, SAMS Publishing.

97

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