0% found this document useful (0 votes)
214 views187 pages

Lab Manuals of OOP - New

This document outlines 14 labs covering topics in object oriented programming including functions, pointers, structures, classes, inheritance, polymorphism, and templates. It provides an overview of the topics and objectives covered in each weekly lab. Lab 1 focuses on functions, pointers, and structures including defining and calling functions, passing arguments by value and reference, using pointers, and defining and accessing structure members. The document provides guidance on tasks and tools for practicing code writing, compilation, and testing skills for each lab topic.

Uploaded by

Hira Faisal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
214 views187 pages

Lab Manuals of OOP - New

This document outlines 14 labs covering topics in object oriented programming including functions, pointers, structures, classes, inheritance, polymorphism, and templates. It provides an overview of the topics and objectives covered in each weekly lab. Lab 1 focuses on functions, pointers, and structures including defining and calling functions, passing arguments by value and reference, using pointers, and defining and accessing structure members. The document provides guidance on tasks and tools for practicing code writing, compilation, and testing skills for each lab topic.

Uploaded by

Hira Faisal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

Capital University of Science and Technology, Islamabad

Department of Computer Science/Software Engineering,


Faculty of Computing

Lab Manuals for Object Oriented Programming


(CS1141/SE1141)
Spring 2021
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Contribution

The manual was last updated on January 14th, 2022 by:


Mr. Khayyam Gohar (Reviewed + Revised) and Mr. Syed Abdul Basit (Revised)

2
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Outline

Sr.no Week Labs Page no.

1 1 LAB 1 - Functions, Pointers, and Structure 5


2 2 LAB 2 - Introduction to Classes and Objects 22
3 3 LAB 3 - Abstraction I (Access Specifiers, Constructors and 34
Destructors)
4 4 LAB 4 - Abstraction II (Constructor Overloading and Copy 46
Constructors)
5 5 LAB 5 - Abstraction III (Shallow Copy / Deep Copy and Working 60
with Arrays)
6 6 LAB 6 - File Handling 74
7 7 LAB 7 - Reusability I (Inheritance Types) 85
8 8 LAB 8 - Reusability II (Multi-level Multiple) 97
9 9 LAB 9 - Reusability III (Function Overloading Overriding) 110
10 10 LAB 10 - Reusability IV (Polymorphism) 122
11 11 LAB 11 - Reusability V (Relationships) 136
12 12 LAB 12 - Reusability VI (Templates) 146
13 13 LAB 13 - Static keyword 155
14 14 LAB 14 - Friend Functions and Friend Classes 166
15 15 LAB 15 - Operator Overloading 170

3
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-01)
Functions, Pointers, and Structure – Recap

4
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
72.
Activity Time-
boxing 73.
Objective of the
Experiment 74.
Concept
Map 84.1
Reusability/ Modularity of
Code 84.2
Function Prototype and Function
Definition 84.3
Function Arguments and
Parameters 84.4
Returning a Value from a
Function 94.5
Pass by Value and Pass by
Reference 104.6
Pointers
114.7
Structures
124.7.1
How to define a structure in C++
programming? 124.7.2
How to define a structure
variable? 124.7.3
How to access members of a
structure? 134.7.4
Structure
Example 135.
Homework before
Lab 145.1
Problem solution
modeling 145.2
Practices from
home 145.2.1
Task
1 145.2.2
Task
2 146.
Procedure &
Tools 156.1
5
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Tools
156.2
Setting-up Visual Studio 2008
156.3
Walk-through Task
156.3.1
Writing
Code 156.3.2
Compilation
166.3.3
Executing the
Program 167.
Practice
Tasks 167.1
Practice Task 1
167.2
Practice Task 2
167.3
Practice Task 3
167.4
Out
comes 177.5
Testing
178.
Evaluation Task (Unseen) [Expected time = 60
mins] 189.
Evaluation
Criteria 1810.
Further
Readings 1810.1
Books
1810.2
Slides
18

6
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 1: Functions, Pointers, and Structure - Recap


1. Introduction
C++ programming that you studied in the previous semester is purely based on writing a set of instructions
in a particular sequence such that the output is based on the sequence of the written statements. If this
sequence of instructions is modified then it could have a large impact on the resulting program. Often a
situation arises where we intend to use a particular chunk of code again and again in a single program. In
this scenario using sequential programming the programmer is forced to copy-paste the code in various
locations of the source file.
Although this is a solution, it is not a practical one because it causes the code to become lengthy,
unmanaged, poorly structured and difficult to understand. In such a situation function handling offers an
attractive and easy to implement alternative that is widely accepted and promoted by programmers of all
languages.
This lab is a refresher course on the use of functions, pointers and building logic. The functions that are
designed will receive variables and arrays from the user. The function will perform some processing on the
provided data and return results back to the main program.
The importance of this lab can be highlighted through the fact that functions play a pivotal role in the
establishment of classes, objects and their manipulations. A large portion of object oriented programming
is based on manipulating variables using functions. In the later part of this lab the use of pointers has been
emphasized. Concepts relating to pointers, memory access, using arrays with pointers have been presented.
Relevant Lecture Readings
● Lectures: 1, 2
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Chapters: 5, 10

2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 15 mins 15 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Task 25 mins 25 mins
7 Practice tasks 15 + 15 + 20 + 35 (mins) 85 mins
8 Evaluation Task 40 min for two task 50 mins
Total Time 170 Mins

3. Objective of the Experiment


After completing this lab the student should be able to:
● Understand the purpose/ advantage of creating a function.
● Understand the difference between a function definition and prototype.
● Understand the difference between a parameter and an argument.
● Understand how a function is created and called.
7
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● Understand how values are passed by value and by reference to a function. Returning the values
thereafter.
● Use pointers and manipulate variables using pointers.
● Use an array with pointers in a function
● Understanding of structure

4. Concept Map

4.1 Reusability/ Modularity of Code

Computer programmers have always devised mechanisms through which they can make their code more
understandable and then reusable. In this regard functions offer a very popular and easy mechanism of
introducing the above goals. Function handling operates on the concept of provision of service/
functionality. We can call the services of a function by providing the required data and in result getting the
promised service from the function.

Reusability of code means devising methods through which you can use code again and again without
having to copy-paste in the source file. Modularity of code means dividing the code into small, manageable
and easy to understand segments.

4.2 Function Prototype and Function Definition


The creation of a function is based on two similar yet distinct statements called a function definition and
function prototype.
A function prototype explains only how a function will be called and what data type it will return. A function
definition on the other hand matches the function prototype and also includes a function body.
For example the following is the function prototype of a function that finds the sum of two integers passed
to it:
void addtwo(int, int);
The following is the function definition of the above defined function:
void addtwo (int a, int b){
int c = a+b;
cout<<”Sum is…”<<c;
}

4.3 Function Arguments and Parameters


There are two types of variables a function is related with; namely function arguments and function
parameters. Function arguments are those variables that are provided to a function. These variables are
passed whenever a function is called.
Function parameters are those variables that are created and initialized when parameters are passed to a
function. The scope of a function parameter is always within the body of the function. It should be pointed

8
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

out here that any variable that is created in a function body has a local scope and cannot be accessed outside
the function body. The data type of arguments must match the parameters of a function. In the following
example, variables a and b are parameters of the function addtwo( ).
void addtwo(int a, int b){
int c = a+b;
cout<< c;
}

Now suppose we are calling the same function from within the main().
void main (){
int x=3, y=4;
addTow(x, y);
}

4.4 Returning a Value from a Function


To increase the practical use of functions, a programmer may want the result of a function to be given back
after processing. This process is called returning a value from a function. It is important to remember that
functions can only return a single value (of any data type). If a function will not return a value then it is
necessary to write void before the function name in the prototype and the definition. It is not necessary for
a function to return a value.

For example the following function does not return a value hence the void keyword is used
void addtwo (int a, int b);{
int
c=a+b;

cout<<
c;
}

The following function returns an integer value hence the keyword int is used.

int addtwo (int a, int b);{


int
c=a+b;
return
(c);
}

The value being returned can be displayed by using the following statement from where the function is
9
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

being c
cout<< addrow(x, y);

4.5 Pass by Value and Pass by Reference


All the functions we have discussed until now are pass by value. Pass by value is an argument passing
technique in which the function receives a parameter and works with a copy of the value being provided.
This means if a change is made to the parameter value then no change will not be reflected in the argument.

On the other hand pass by reference is an argument passing technique in which the function works with the
exact variable that is being passed as an argument. This means that even the smallest change in a parameter
will be exactly reflected in the arguments. This further implies that the arguments and the parameters are
tightly coupled.

10
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

4.6 Pointers

Pointers are special kind of variables that are allowed to hold the address of another variable. Because of
their pointing ability pointers are considered very powerful in C++. Pointers can hold the address of another
variable and this is called referencing the memory location. When we attempt to extract values from a
memory location then this is called dereferencing a pointer

Figure 1: The working of a pointer (image courtesy of Wikipedia)

In the figure provided above there is a pointer variable called “a”. This variable is pointing to the memory
address of variable b. The memory address of variable b is 1008. In this diagram you will also note that
the pointer “a” has its own memory address. This is a very important fact because pointers themselves
also require a space in memory. When we write a code on our compilers remember that every computer
has its own memory and the availability of memory space. Our compilers take the help of a memory
manager and allocate space in a memory slot that is available to the system. This means every time we
run the code we may get a different memory allocation.

Consider the code provided

11
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 2: The various operations that can be performed with a pointer. Output is also provided. Memory
addresses may be different depending on the hardware environment

In the code above first a simple integer variable is created. Then an integer pointer is created because we
intend to point to an integer variable. The pointer is then given the address of variable x by using the address
operator. Then we use the dereference operator (*) that directs us to the memory location where the pointer
is pointing to.

4.7 Structures
Structure is the collection of variables of different types under a single name for better visualization of
problem. Arrays is also collection of data but arrays can hold data of only one type whereas structure can
hold data of one or more types.

4.7.1 How to define a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier (name of the structure). Then inside
the curly braces, you can declare one or more members (declare variables inside curly braces) of that
structure. For example:

Here a structure person is defined which has three members: name, age and salary.

4.7.2 How to define a structure variable?


Once you declare a structure person as above. You can define a structure variable as: person bill;
Here, a structure variable bill is defined which is of type structure person.
12
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

4.7.3 How to access members of a structure?


The members of a structure variable are accessed using dot operator. Suppose, you want to access age of
structure variable bill and assign the value 50 to it. You can perform this task by using following code
below:

4.7.4 Structure Example

Output:
13
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

5. Homework before Lab

5.1 Problem solution modeling


Write the pseudo-code of the following task. You are required to bring this code with you and submit
to your lab instructor.

Write pseudo-code for a program that will read number n and print the first n numbers in Fibonacci
sequence. Your task is to also perform checks on the number entered by the user as it should be positive
integer. This condition should also be incorporated in your pseudo-code.

5.2 Practices from home

5.2.1 Task 1
Every moving object possesses a kinetic energy due to its motion. Your task is to write a program to find
the kinetic energy of an object in motion if the mass and the velocity of that object is given. Write a function
to perform the calculation. Your task is to provide the mass and velocity as arguments to the function and
then display the kinetic energy without returning a value.

5.2.2 Task 2
Write a program that creates a function to find the area of a trapezium if the sides a, b and the height h of
the trapezium are provided. The function should return the value of area. The area of a trapezium is ½(a+b)h.
Consider the figure below for further clarification.

14
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

6. Procedure & Tools

6.1 Tools
Visual Studio 2017.

6.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup Visual Studio and make a project named “FindAverage”.

6.3 Walk-through Task [Expected time = 15 mins]


Write a C++ program that creates (in main function) an array of type int having 6 elements. Now write a
function called arr_avg( ) that will find the average of all the elements of the array. This function should
return the average back to the main( ) function. Also write another function called arr_display() that will
display all the elements of the array.

6.3.1 Writing Code


In the source file created in the project “FindAverage” write following C++ code

Figure 3: Function for finding average of values in an array


15
Lab 1: Formatting using Escape Sequences

In the code above note that the two functions use different mechanisms for passing/ using an array. You
can choose the method that suits your code/ situation. The size is passed in both functions because without
the size the functions can easily cross the array bounds. Hence passing the array size is a good practice.

6.3.2 Compilation
Write a program to find the power of a number if the base and exponent is provided in the main function.
Use pass by value mechanism to compute the power and return the results back to the main function then
display the result in main function.

6.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 4: Final output of FindAverage program.

7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab01.

7.1 Practice Task 1 [Expected time = 10 mins]


Write a program to find the greatest common factor if the two numbers are provided in the main function.
Use pass by value mechanism to compute the greatest common factor and return the result back to the main
function then display the result in the main function.

7.2 Practice Task 2 [Expected time = 10 mins]


Write a program to find the product of 2 power numbers if the base and the exponent of these numbers are
provided in the main function, also check that the base of both the power number are the same, as the
product of 2 power numbers can only be calculated if their base is the same. Use pass by reference
mechanism to compute the product of these power numbers then display the result in main function.
Note: Your function should not return a value.

7.3 Practice Task 3 [Expected time = 10 mins]


Create a structure course with some attributes i.e course_ID, course_title, credit_hrs etc.. Then Implement
following 5 functions (Known as CRUDS operations which means CREATE, READ, UPDATE, DELETE,
SEARCH operations):
1. addAStudent
2. updateAStudent

16
Lab 1: Formatting using Escape Sequences

3. deleteAStudent
4. searchAndDisplayAStudent
5. displayAllstudents

After that, create an array of 5 courses in main function. Create a menu in main function to enable user to
select and perform the operations we created above. Program must not exit until and unless user wants to
do so.

Sample Menu:
Main Menu
---------------

Press 1 to add a Course


Press 2 to update a Course
Press 3 to delete a Course
Press 4 to search and display a Course
Press 5 to display all Courses
Press e to exit the program

7.4 Out comes


After completing this lab, students will be able to use functions and also understand the concept of
parameters, Arguments and returning of values. Students should also be comfortable with pointers and their
use in functions.

7.5 Testing
Test Cases for Practice Task-1

Sample Inputs Sample Outputs


1st Number : 12 Result = 4
2nd Number: 16
Check that the function works with pass by value

Test Cases for Practice Task-2

Sample Inputs Sample Outputs


1st Power Number : Result = 8
Base = 4
Exponent = 2
2nd Power Number:
Base = 4
Exponent = 6 Check that the function works with pass by reference

Table 2: Confirmation of practice tasks T1, T2, T3, T4


Practice Tasks Confirmation Comments
T1
T2
T3

17
Lab 1: Formatting using Escape Sequences

T4

8. Evaluation Task (Unseen) [Expected time = 60 mins]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. Task No Description Marks
No.
1 4.1 Problem Modelling 20
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with Testing 10
4 7.2 Practice task 2 with Testing 10
5 7.3 Practice task 3 with Testing 10
6 7.4 Practice task 4 with Testing 15
7 8 Evaluation Tasks (Unseen) 20
8 Good Programming 10
Practices
Total Marks 100

10. Further Readings

10.1 Books
Text Book:
Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

18
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-02)
Introduction to Classes and Objects

19
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction 212. Activity Time boxing 213. Objective of the Experiment 214.
Concept Map 224.1 Object 224.2 Data Members 224.3 Member Function 224.4
Constant Member Function 234.5 Class 234.6 Encapsulation 245. Homework
before Lab 265.1 Problem solving Modelling 265.1.1 Problem description 265.2
Practices for home 265.2.1 Task-1 266. Procedure & Tolls 266.1 Tools
266.2 Setting-up Visual Studio 2008 266.3 Walkthrough Task
266.3.1 Writing Code 276.3.2 Compilation 286.3.3 Executing the
Program 287. 288. Practice Tasks 288.1 Practice Task 1 288.2 Practice Task 2
288.3 Out comes 288.4 Testing 299. Evaluation Task (Unseen) 2910.
Evaluation Criteria 2911. Further Readings 3011.1 Books 30

20
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 2: Introduction to Classes and Objects


11. Introduction

The programming that you have understood in your computer programming course, allows you to design a
program by assembling a sequence of instructions. This is the way in which traditional programming works,
but now there is clear paradigm shift towards an object based approach. The new object oriented approach
allows you to model your program in a way in which objects, their relationships and the functions that they
operate are clearly visible to the programmer. Perhaps the greatest advantage of this approach is that it gives
an extended modular concept in which the interface is made public while the implementation details are
kept hidden.

This allows the program to grow in size without becoming too cumbersome. Previously, when a program
grew beyond a certain size it became almost impossible to understand and extend especially when the
programmer had forgotten the minor concepts constructing the program. Here, it should be understood and
acknowledged that programs are not disposable entities they have a life beyond what is normally expected.
Hence designing a program that can be easily extended, modified and interfaced with other systems is a
very important characteristic of any well written program. This lab has been designed to give in-depth
knowledge of how to make classes, objects and their interrelations. The concept map provides all the crucial
details that are required for the completion of this lab.
Relevant Lecture Readings:
a) Revise Lecture: No. 3 and 4
b) Text Book: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 195-201

12. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 15 mins 15 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Task 30 mins 25 mins
7 Practice tasks 25 + 25 + 30 (mins) 80 mins
8 Evaluation Task 45 min 45 mins
Total Time 170 Minutes

13. Objective of the Experiment


After completing this lab, the student should be able to:
● Clearly understand the purpose and benefits that OOP has to offer
● Understand the concept of a class and objects
● Develop a basic class with fundamental data members

21
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● Develop a basic class with a number of member functions
● Use a constant member function
● Separate the implementation section of a function
● Use the class objects and member functions to provide and extract data from an object
● Experiment with classes and objects

14. Concept Map

14.1 Object

In OOP an object is a very much like a real world object. An object can be defined as a collection of state
and behavior. For example, consider the example of a cat. A cat is has both a state and behavior. The state
of a cat is its attributes namely color, breed, gender, age, weight, height, etc. Whereas the behavior of a cat
is its sound, eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique
characteristics and behaviors.

In programming an object is a collection of variables and functions that together have a unique purpose of
identifying a distinctive entity.

14.2 Data Members

Again referring to the concept of an object and the example of a cat. The cat had a number of characteristics
or attributes that can be used to identify a cat. In programming these attributes can be programmed by using
regular variables that are called data members. A class can be composed of a number of data members of
various types. The data members of a class are private by default i.e. they are not directly accessible outside
the class.

Here it is important to point out that often people casually refer to these as variables, which is a wrong
terminology. These should only be called data members or class variables.

14.3 Member Function


Again referring to the concept of an object and the example of a cat. The cat had a number of behaviors or
things that a cat does. In programming these behaviors can be programmed by using functions that are
called member functions. A class can be composed of a number of member functions of various types.
Overloading of member functions is also permitted in C++. The implementation section of member
functions can be separated whereby the body of the function is created outside the class but the function
prototype has to exist in the body of the class. The implementation section is separated by writing the return
type followed by class name. This is further followed by scope resolution operator :: and then the remaining
function definition.

using namespace std;

22
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

class myclass
{
int datamember;

int memberfun(int); // Function prototype


};

int myclass :: memberfun (int x) // Note the scope resolution operator


{
... // Function body
}

void main( )
{

14.4 Constant Member Function


A constant member function is just like a conventional function except it is a read only function. This means
that the function cannot modify anything related to the object. But the member function can still perform
all reading activities related to the object. Such type of functions are generally created when the programmer
wishes to only read/ display the data members on the screen. Given below is the syntax for creating these
constant member functions.

void addtwo ( ) const //Note the keyword const


{
cout<<”The sum is= ”<<s;
}

14.5 Class
A class is a co0llection of data members and member functions. A class is used to define an abstract data
type. This abstract data type is used in the construction of an object which is used to access all the data
members and member functions. A class has to be created before it can be used. Provided below is the
syntax for creating a class:

23
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

14.6 Encapsulation
Encapsulation is a very important design goal because of which OOP is preferred over conventional
programming. Encapsulation is a quality because of which data and function are stored in a single unit
commonly known as a class. This unit/ bundle ensure that the data is not openly accessible to the outer
world. The access is provided by the functions that are part of the unit/bundle. This means that the functions
work like doors in a room. You can prevent thieves from breaking in. Only those people can enter who

24
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
come through the door.

25
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

15. Homework before Lab

15.1 Problem solving Modelling


Design the following problem by listing down the data members and the member functions. You are
required to bring this task with you and submit to the lab instructor.

15.1.1 Problem description


List down the data members and member functions of a class identifying an Android phone. You are
allowed to suppose the data members and the member functions of the class. Also create a single member
function that will display the entire class data members. You will be graded on the quality and clarity of
your design.

15.2 Practices for home

15.2.1 Task-1
Identify the data members and member functions for a submarine sandwich class. The class should have all
the relevant attributes and qualities required for a sandwich object. Try to be imaginative in your design.
For example consider various sauces, Mortadella, salads, cheese and other fillings etc.

16. Procedure & Tolls

16.1 Tools
Visual Studio 2008.

16.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “arc”.

16.3 Walkthrough Task [Expected time = 25 mins]


Write a program that creates a class called arc. The data members of the class are radius, angle and
arc_length of the arc is provided. Write three functions that set the respective values, and then write a single
constant function that will read the values.

26
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

16.3.1 Writing Code


In the source file created in the project “arc” write the following C++ code:

Figure 1: Class for creating an arc with its relevant data members

27
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
16.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.

16.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

17. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab02

17.1 Practice Task 1 [Expected time = 25 mins]


Create a class Android_Device. The data members of the class are IMEIno (int), Type (String), Make
(String), Modelno (int), Memory(float), Operating_System(String). Then Implement member functions to:

1. Set the values of all data members.


2. Display the values of all data members

17.2 Practice Task 2 [Expected time = 25 mins]

Write a class called quadrilateral. Your task is to store the length of all the sides of the quadrilateral and the
value of the 2 opposite angles within the quadrilateral. Then implement member functions:

1. To compute the area of the quadrilateral.


2. To compute the parameter of the quadrilateral.
3. A constant function that will display the length of all the sides, the angles, the parameter of the
quadrilateral and area of the quadrilateral.
4. Create setter and getter methods.

Demonstrate the use of the object in the main function. Make sure that the function names are meaningful
and self-descriptive.

17.3 Out comes


After completing this lab, students will be able to design a basic class with data members and member
functions.

28
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
17.4 Testing
Now you need to perform the following test cases for all practice tasks mentioned above. The test cases
have been made available in Table 2.

Test Cases for Practice Task-1


Sample Inputs Sample Outputs
Set the following values IMEIno = 12345678901234
IMEIno = 12345678901234 Type = Tablet
Type = Tablet Make = Chuwi
Make = Chuwi Modelno = V8 HD
Modelno = V8 HD Memory = 860.5
Memory = 860.5 Operating System = Android Ice cream Sandwich 4.0.4
Operating System = Android Ice cream
Sandwich 4.0.4

Test Cases for Practice Task-2

Sample Inputs Sample Outputs


A = 30 A = 30
B = 150 B = 150
C = 140 C = 140
D = 20 D = 20
Angle1 = 80 Angle1 = 80
Angle2 = 110 Angle2 = 110
Parameter = 340
Area = 3345.34

18. Evaluation Task (Unseen) [Expected time = 60 mins]

The lab instructor will give you unseen task depending upon the progress of the class.

19. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).

Table 3: Evaluation of the Lab

Sr. No. Task No Description Marks

1 4.1 Problem Modelling 20


2 6 Procedures and Tools 5

29
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
3 7.1 Practice task 1 with Testing 10
4 7.2 Practice task 2 with Testing 20
5 8 Evaluation Tasks (Unseen) 15
6 Good Programming 10
Practices
Total Marks 80

20. Further Readings


20.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

20.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at: \\fs\lectures$

30
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-03)
Abstractions I
(Access Specifiers, Constructors and Destructors)

31
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
332.
Activity Time-
boxing 333.
Objective of the
Experiment 334.
Concept
Map 344.1
Access Specifiers – Public and Private
Access 344.2
Constructors
354.3
Destructors
355.
Homework before
Lab 365.1
Practices from
home 366.
Procedure &
Tools 376.1
Tools
376.2
Setting-up Visual Studio 2008
376.3
Walkthrough Task
376.3.1
Writing
Code 376.3.2
Compilation
386.3.3
Executing the
Program 387.
Practice
Tasks 387.1
Practice Task 1
387.2
Evaluation Task (Unseen)
408.
Evaluation
Criteria 40

32
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 3: Access Specifiers, Constructors and


Destructor

21. Introduction
Programming that you studied in the previous semester does not strongly support programming practices
like encapsulation and data hiding. In fact these features are almost nonexistent in sequential programming.
Object Oriented Programming is purely based on these practices and enforces these practices through
various techniques. In this regard access specifiers play a very important role because they are the first line
of defense in secure programming. This lab is designed to teach three very basic yet essential concepts of
OOP namely access specifiers, constructor and destructors. Access specifiers provide a technique through
which we can restrict access to data members and member functions. After enforcing access it is important
to reduce our reliance on too many member functions. Constructors offer a very attractive and easy to
implement technique through which we can take steps call procedures whenever an object is created. The
use of constructors is preferred over the use of member functions because constructors are called
automatically and hence they can invoke further functions whereas simple member functions have to be
called sequentially and explicitly one by one every time an object is created. Similarly this lab also focuses
on the use of destructors that are called whenever an object goes out of scope. In this the lab the students
will be familiarized with the use of access specifiers, constructors and destructors.
Relevant Lecture Readings:
● Lectures: 3, 4, 5, 6
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 201-212

22. Activity Time-boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 15 mins 15 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Task 30 mins 25 mins
7 Practice tasks 80 mins 80 mins
8 Evaluation Task 45 mins 45 mins
Total Time 170 Minutes

23. Objective of the Experiment


After completing this lab the student should be able to:
● Clearly understand the purpose and importance of access specifiers
● Develop a class by correctly using/ enforcing access specifiers
● Differentiate between the public and private access specifiers
● Understand the importance of constructors

33
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● Understand the importance of destructors


● Use a basic constructor
● Use a basic destructor

24. Concept Map

24.1 Access Specifiers – Public and Private Access


Access specifier also known as access modifier provides a technique for enforcing access control to class
members (data members and member functions). The use of access specifiers enforces encapsulation and
data hiding. C++ provides three access specifiers i.e. public, private and protected. In this lab we will only
cover the public and the private access specifier. The protected specifier is left for future discussions.

The public access specifier is the one that provides unrestricted access to the class members. While the
private access specifier provides a very strict/ restricted access to class members. All the class members
that are written under the public access can be accessed both inside and outside the class without any
restriction. On the other hand all the class members written as private are accessible inside the class but are
not accessible outside the class. The best and most common way of accessing private data members is
through the use of a public functions.

When we are discussing access specifiers it must be pointed out that by default classes are private whereas
structures are public. Hence if you do not write private then your listed class members are considered
private in a class.

The correct convention for the use of access specifiers is that data members are kept private whereas
functions are kept public. Hence you are providing a public interface for accessing restricted items in a
class.

using namespace std;


class myclass
{
private:
int datamember; //Private data member public:
int memberfun(int); // public member function
};

int myclass :: memberfun (int x) // This function is still public because its prototype is public
{
datamember=x;
}

void main( )
{
myclass obj;

34
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

myclass::datamember=10; //Syntax Error: private member obj.memberfun(10);


}

24.2 Constructors
A constructor is a function that is automatically called when an object is created. This function can exhibit
the regular behavior of any function except that it cannot return a value. The reason why constructors are
needed is that unlike regular functions which need to deliberately called, a constructor will be automatically
called when an object is created. Every constructor has a body from where we can call regular member
function a very important question which is often asked is that how does the compiler know that the
constructor function needs to be called automatically? The answer is very simple. A constructor is a function
that has the same name as the class. Whenever an object is created the compiler searches for a function
having the same name as the class i.e. the constructor. Given below is a sample code that shows the class
constructor. Generally the constructor is defined as public. Also the constructor can be overloaded like a
regular member function. An important point regarding a constructor is that it cannot return a value. In fact
writing the keyword void is strictly prohibited.

using namespace std;


class myclass
{
private:
int datamember; //Private data member public:
myclass( ); //Class constructor
{
cout<<”Hello you have called the class constructor”;
}
};

void main( )
{ myclass obj; }

24.3 Destructors
Constructors are designed to help initialize/ create an object. Destructors on the other hand do exactly the
opposite. Destructors are called whenever an object goes out of scope. When this happens it is necessary to
perform cleanup procedures especially when you have used dynamic memory or you have been working
with pointers in your code. The destructor function can be used to free up memory that you have allocated
or dereference pointers that were referenced. The rules for a destructor are as follows:
● They have the same name as the class just simply preceded by a tilde (~)
● They can take no arguments
● They cannot return anything, not even void

using namespace std;

35
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

class myclass
{
private:
int datamember; //Private data member public:
myclass( ); //Class constructor
{
cout<<”Hello you have called the class constructor”;
}
~myclass( ); //Class constructor
{ cout<<”Hello you have called the class destructor”; }

25. Homework before Lab

25.1 Practices from home


Your task is to carefully understand the code provided. Analyze the code and suggest any corrections that
may be needed. There are both syntax and logical errors in the code so consider both when designing the
correct solution. Submit the correct code to the lab instructor.

class student{
int age;
int cnic;
int semester;
char name;
public:
int setall(int a, int c, int s, int sem, char n) const
{
age = a;
cnic = c;
semester = s;
name = n;
}
}
int myclass :: displayall ( ){
cout<<”The entered data is”<<student.data;
}
void main( ){Student obj; obj::setall( ); obj.displayall( ); obj.setage(); Student
anotherobj;Student::anotherobj::setall();
}

25.2 /Practices from home


Create a class “Vehicle” having:

36
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● “LisencePlate_No”, “Model_No”, “Type”, and “Color” as private data members.


● Parameterized constructor assigning default values to the data members
● No-Argument constructor assigning default values to the data members
● Default constructor assigning default values to the data members
● Public member functions: Register Vehicle, Update Vehicle, Delete Vehicle, and Search Vehicle
NOTE: The values required should be obtained from the user in “void main ()” function and each data
member should have a setter and a getter through which you are required to perform the member function

26. Procedure & Tools

26.1 Tools
Visual Studio 2017.

26.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup Visual Studio and make a project named “pizza”.

26.3 Walkthrough Task [Expected time = 40 mins]


Write a program that creates a class called pizza. The data members of the class are size, toppings, price,
thickness, and extra toppings. Through the use of a constructor initialize the class object. Determine what
is public and private in the class.

26.3.1 Writing Code


In the source file created in the project “pizza” write the following C++ code:
class pizza
{ private: int size, price, thickness; string topping;
public:
void setsize() ,
{ cout<<"Enter size of pizza: ";
cin>>size; }
void setprice()
{ cout<<"Enter price of pizza: ";
cin>>price; }
void setthickness()
{ cout<<"Enter thickness of pizza: ";
cin>>thickness; }
void settopping()
{ cout<<"Enter toppings of pizza: ";
cin>>topping; }
void display() const
{ cout<<"The ordered pizza details are: "; cout<<"\nSize: "<<size; cout<<"\nPrice:
"<<price; cout<<"\nTopping:"<<topping; cout<<"\nThickness:"<<thickness<<"\n"; }
pizza() //class constructor: cannot have a return type
{ setsize(); setprice(); setthickness(); settopping(); }

37
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

};
void main()
{ pizza obj; obj.display( ); }

Figure 1: The pizza class demonstrating the use of a constructo

26.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.

26.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 2: Final output of pizza program.

27. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab03

27.1 Practice Task 1 [Expected time = 20 mins]


Write a C++ program for a new ice cream vendor called PopSalon. The management of PopSalon has
decided that they are going to sell their popcorn in 11 different flavors namely: chocolate, English toffee,
salted caramel, caramel, jalapeno, cheese, spiced cheese, plain sated, buttered, salt and pepper, and garlic.
Carefully design the program by observing the following rules.

38
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● PopSalon is charging Rs. 100 for small pack, Rs. 250 for medium sized pack, Rs. 500 for large
sized pack and Rs. 750 large size tin pack. Hence you will need a function to determine the size of
the pack and based on that the price. If a user enters option number other than the ones displayed,
your program should display an invalid input message and ask the user to re-enter the option
number.
● PopSalon allows its customers to purchase a gift wrapper with their popcorn. If the customer wants
to purchase the wrapper he will have to pay an additional Rs 50. This amount should be added to
the total amount payable by the user.
● If the customer asks for chocolate sauce, caramel sauce, or melted cheese as an additional topping
then he will have to pay an additional amount of Rs. 50, Rs. 30 and, Rs. 60 respectively. Design a
function that will be called if the customer chooses an additional topping.
● The program should show a menu that asks the customer for his requirements and then displays the
final payable amount with full details about the flavor, the size of the pack and details regarding
any additional toppings.
● For service quality inspection and monthly product promotions, the program should ask the user to
enter his/her contact details including name, mobile number and email address, and select between
the options good, neutral and bad against the quality of the service provided.
● In the end create a class destructor that displays a thank you message to the user. Design your
program using sound OOP practices. Carefully determine the data members, member functions,
access specifiers, activities to be performed in the constructor. Make sure that you use good naming
conventions in your code. A good design can earn you higher marks.

27.2 Outcome:
After completing this lab, students will be able to design a class that correctly implements class members
by observing access specifiers. The students will also be familiar with the use of a constructor and
destructor.

27.3 Testing
Test Cases for Practice Task-1

Sample Inputs Sample Outputs


Flavour = Chocolate Your choice of Popcorn is:
Pack Size = Medium Flavour = Chocolate
Additional Toppings = No Pack Size = Medium
Wrapper Required = No No Additional Toppings Required !
_______________________ No Gift Wrapper Required !
Product Promotion Details Total Bill = 250
Customer Name = Ali ____________________________
Mobile Number = 0300-4004563 Thank you for visiting PopSalon!
Quality of Service = Good

39
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Flavour = chocolate Your choice of Popcorn is:


Pack Size = medium Flavour = Chocolate
Additional Toppings = Chocolate Pack Size = Medium
Wrapper Required = No No Additional Toppings = Chocolate
_______________________ No Gift Wrapper Required !
Product Promotion Details Total Bill = 300
Customer Name = Ali ____________________________
Mobile Number = 0300-4004563 Thank you for visiting PopSalon!
Quality of Service = Good
Flavour = strawberry Invalid Input
Pack Size = medium ____________________________
Additional Toppings = No Thank you for visiting PopSalon! Please Try Again
Wrapper Required = No
_______________________
Product Promotion Details
Customer Name = Ali
Mobile Number = 0300-4004563
Quality of Service = Good

Table 2: Confirmation of practice tasks T1

Practice Tasks Confirmation Comments


T1

27.4 Evaluation Task (Unseen) [Expected time = 60 mins]

The lab instructor will give you unseen task depending upon the progress of the class.

28. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.

Table 3: Evaluation of the Lab

Sr. No. Task No Description Marks

1 4.1 Problem Modelling 10


2 6 Procedures and Tools 5

40
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

3 7.1 Practice task 1 with Testing 50


4 8 Evaluation Tasks (Unseen) 15
5 Good Programming 10
Practices
Total Marks 90

29. Further Reading

29.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

29.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\fs\lectures$

41
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-04)
Abstraction II
(Constructor Overloading and Copy Constructors)

42
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
452.
Activity Time
boxing 453.
Objective of the
Experiment 454.
Concept
Map 454.1
Function
Overloading 454.2
Constructor Overloading – Parameterized and Nullary
Constructors 464.3
Copy
Constructors 475.
Home Work before
Lab 475.1
Practices from
home 476.
Procedure &
Tools 476.1
Tools
476.2
Setting-up Visual Studio 2008
476.3
Walkthrough Task
476.3.1
Writing Code
486.3.2
Compilation
496.3.3

497.
Practice
Tasks 497.1
Practice Task 1
507.2
Practice Task 2
517.3
Outcomes
527.4
Testing
528.

43
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Evaluation Task (Unseen)


539.
Evaluation
Criteria 5310.
Further
Reading 5410.1
Books
5410.2
Slides
54

44
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 04: Constructor Overloading and Copy


Constructors
30. Introduction
In the previous lab a detailed practice session was conducted that focused on access specifiers and
constructors. Constructors are special functions that are automatically called when an object is created. This
lab is geared towards an extended use of constructors through overloading. Another flavour of constructors
is the copy constructor which creates an object by using a previously implemented object. This can be
accomplished through the use of a copy constructor.

Relevant Lecture Material


● Lectures: 6, 7, 8
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 212-213, 216-217

31. Activity Time boxing


Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
5.1 Evaluation of Design 25 mins 25 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 35 mins 35 mins
7 Practice tasks 40 + 10 (mins) 50 mins
8 Evaluation Task 55 mins 55 mins
Total Time 170 Minutes

32. Objective of the Experiment


After completing this lab the student should be able to:
● Develop a constructor and then overload it
● Understand the difference between a parameterized constructor and non-parameterized
constructor
● Develop a copy constructor and facilitate the copying of data from one object to the other.

33. Concept Map

33.1 Function Overloading


Function overloading is an advanced concept in modern languages where two functions can have the same name. The
question that arises here is that how does a compiler know which function to call. The simple answer is that the
function calling is determined based on the type of parameters/ the number of parameters being passed/ order of
parameters being passed. Hence two functions can have the same name but there must be a difference in the number

45
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

of parameters, type of parameters or the order of parameters. For example in the function prototypes below the function
fun( ) has been overloaded and its different flavours are presented.
int fun (int, float, float);
int fun (int, float);
int fun (float, float, int);
It is important to highlight here that if two functions have a different return type then it does not mean that they are
overloaded. For a function to be overloaded it is necessary for the function to exhibit changes in the parameters.

33.2 Constructor Overloading – Parameterized and Nullary Constructors


Constructors are designed to help initialize/ create an object. A constructor is a special function that is
automatically called upon the creation of an object. The important fact that needs to be communicated is
that constructors do not have a return type. In fact using the keyword void is also prohibited.
Constructors are of two types namely:
● Nullary Constructors / Parameterless Constructors – Those constructors that do not need a parameter
to be called.
● Parameterized Constructors – Those constructors that require parameters for their calling
Inside a class C++ allows us to overload a constructor just like any other function. This means in the same
class you can have a nullary constructor alongside a parameterized constructor. Consider the code below
for further reference.
class example
{
private:
int one;
int two;
float three;
public:
example( ) //Nullary constructor
{
...
}
example (int on, int tw, float th) //Overloaded Constructor:
parameterized ->1
{
}
};
};
int main()
int main()
{
{
example obj; //Creation through nullary constru
example obj; //Creation through nullary constru
example obj2(1, 2, 3.3); //Creation through first parameterized
example obj2(1, 2, 3.3); //Creation through first parameterized
constru
constru
example obj3(1, 3.3, 2); //Creation through Second parameterized
example obj3(1, 3.3, 2); //Creation through Second parameterized
constru
constru
return 0;
return 0;
}
}

46
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

33.3 Copy Constructors


Copy constructors provide a function through which you can create a new object from an existing already
created object. This feature is commonly used in simple programming and hence its need can arise at any
time when working with objects. C++ provides a default copy constructor that will assist in the copying of
simple objects. For example objects that do not use pointers or arrays. Although the default copy constructor
will copy any type of object but it is strongly recommended that the copy constructor be used only for
objects that have non pointer data members. The default copy constructor performs a member by member
copy i.e. the copy constructor creates an exact copy where data members are copied one by one to the new
object. Always remember that in copy constructors the original object is maintained in its original state and
the copy changes are only exhibited in the newly created object. In this lab we will just restrict ourselves to
the use of the default copy constructor.
The default copy constructor can be explicitly called as follows:

class obj2(obj1); // Function calling notation


class obj2 = obj1; //Assignment statement notation

Both statements create an object of the class. Of course any of the above statements can be used for copying
an object into another object.
Caution: The copy constructor is always called at the time of creating a new object. If at any time after the
creation of objects you copy contents of one object to the other, then the copy constructor is not called. We
will discuss more on this in future lectures.

34. Home Work before Lab


Provided below is a statement for a program which you will code and submit to your lab instructor.

34.1 Practices from home


Your task is to create a class called examination. The class has data member’s duration, credit_hours, course
title, month, date, year and time. Your task is to create the individual member functions and call them using
the class constructor. Be very vigilant in determining the access specifiers for the data members and member
functions.

35. Procedure & Tools

35.1 Tools
Visual Studio 2017.

35.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup Visual Studio and make a project named “student”.

35.3 Walkthrough Task [Expected time = 35


mins]
Write a program that creates a class called student. The data members of the class are name and age.

47
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● Create a nullary constructor and initialize the class object.


● Create a parameterized constructor that can set the values being passed from the main function.
● Create a display function called showAll( ) which will be used to show values that have been set.
Use the default copy constructor to show that copying of simple objects can be accomplished through the
use of the default copy constructor.

35.3.1 Writing Code


In the source file created in the project “student” write the following C++ code:

class student
{
private:
string name;
int age;
public:

student() //Nullary constructor


{
cout<<"Enter name ";
cin>>name;
cout<<"\nEnter age ";
cin>>age;
}
student(string n, int a) //parameterized Constructor
{
name=n;
age=a;
}
void showAll()
{
cout<<"\nName= "<<name;
cout<<"\nAge= "<<age;
}; }
};
int main()
{int main()
{ student s1; //Creation through nullary constructor
student s1;
student s2("Ali", //Creation
30); throughthrough
//Creation nullary constructor
parameterized
student
constructor s2("Ali", 30); //Creation through parameterized
constructor
s1.showAll ();
s1.showAll ();
s2.showAll ();
s2.showAll ();
student s3(s1); //Calling copy constructor for s3
student s3(s1);
s3.showAll (); //Calling copy constructor for s3
s3.showAll
return 0; ();
} return 0;
}
48
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: The student class demonstrating the use of a parameterized and nullary constructor. Also note
the default copy constructor being used

35.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.

35.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 2: Final output of student program.

36. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab04

49
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

36.1 Practice Task 1 [Expected time = 40 mins]

In the above given picture of a passport there is a machine readable code at the bottom of the passport. This code
is a set of 44 characters per row. Following are the contents embedded into this code:
● The only characters used are A–Z, 0–9 and the filler character <.
● The format of the first row is:

Position Lengt Character Meaning


s h s
1 1 alpha P, indicating a passport
2 1 alpha+< Type (for countries that distinguish between different types of
passports)
3–5 3 alpha+< Issuing country or organization (ISO 3166-1 alpha-3 code with
modifications)
6–44 39 alpha+< Surname, followed by two filler characters, followed by given
names. Given names are separated by single filler characters

● In the name field, spaces, hyphens and other punctuation are represented by <, except apostrophes, which
are skipped. If the names are too long, names are abbreviated to their most significant parts. In that case,

50
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

the last position must contain an alphabetic character to indicate possible truncation, and if there is a given
name, the two fillers and at least one character of it must be included.
● The format of the second row is:
Position Lengt Characters Meaning
s h
1–9 9 alpha+num+< Passport number
10 1 numeric Check digit over digits 1–9
11–13 3 alpha+< Nationality (ISO 3166-1 alpha-3 code with modifications)
14–19 6 numeric Date of birth (YYMMDD)
20 1 num Check digit over digits 14–19
21 1 alpha+< Sex (M, F or < for male, female or unspecified)
22–27 6 numeric Expiration date of passport (YYMMDD)
28 1 numeric Check digit over digits 22–27
29–42 14 alpha+num+< Personal number (may be used by the issuing country as it
desires)
43 1 numeric Check digit over digits 29–42 (may be < if all characters are <)
44 1 numeric Check digit over digits 1–10, 14–20, and 22–43

● The check digit calculation is as follows: each position is assigned a value; for the digits 0 to 9 this is the
value of the digits, for the letters A to Z this is 10 to 35, for the filler < this is 0. The value of each position
is then multiplied by its weight; the weight of the first position is 7, of the second it is 3, and of the third it
is 1, and after that the weights repeat 7, 3, 1, and so on. All values are added together and the remainder of
the final value divided by 10 is the check digit.
Write a program that uses accepts a given Machine Readable Code and using a class stores the following 11 parts of
a passport separately after extraction as private data members:
1. Full Name
2. Passport Number
3. Nationality
4. Gender
5. Date of Birth
6. Country of Issuance (Passport Issuance)
7. Date of Issuance (Passport Issuance)
8. Date of Expiry
9. Citizenship Number
10. Passport Type
Create setters and getters for all the member variables and a public method named display to display the all the data
members.
Create three constructors as follows:
1. A nullary constructor that initializes the Citizenship Number as “*****-*******-*”.
2. A parameterized constructor that accepts First Name and Second Name and concatenates them into the data
member “Full Name” in its body.
3. A parameterized constructor that will set Gender, Nationality, and Passport Number as sent in parameters.

Create three objects of the class such as:

51
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● First object is initialized with default constructor. The values are then set by calling the setters
● Second object is initialized with the constructor that accepts three arguments.
● Third object is initialized with the constructor that accepts four arguments.

Then display these data members.


Note: Here three constructors are created for different scenarios. Discuss the possible scenarios with the lab
instructor.

36.2 Practice Task 2 [Expected time = 10 mins]


Modify the class created in 7.1, Create a copy constructor to copy a citizenship number. Then in main
function call the copy constructor and observe the outputs.

36.3 Outcomes
After completing this lab, students will be able to construct a class object by using parameterized
constructors. The students will also be familiar with the use of a constructor and destructor.

36.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Using Nullary constructor Your Data is:
Full Name = ALMEERA RAZA
Gender = F
Nationality= PAK
Issuance Date= 12-12-12
Expiry Date=12-12-25
Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=RAZA
Using parameterized constructor (string, string) Your Data is:
FirstName=” ALMEERA” Full Name = ALMEERA ZAHID
LastName=”ZAHID” Gender = F
Nationality= PAK
Issuance Date= 12-12-12
Expiry Date=12-12-25
Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=ZAHID
Using parameterized constructor (char, string, string) Your Data is:
Gender = ‘F’ Full Name = ALMEERA ZAHID
Nationality = “PAK” Gender = F
Passport_Numer= Nationality= PAK
Issuance Date= 12-12-12

52
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

”<PAKZAHID<<ALMEERA<<<<<<<<<<<<<<<<<<<<<<<< Expiry Date=12-12-25


< Country of Issuance= PAK
HJ00000014PAK9912246F12080547880745349760<78” Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=ZAHID

Test Cases for Practice Task-2


Sample Inputs Sample Outputs
Initialize only one of the objects and use it Call the display function using the new object;
for copying values into another object by
using the copy constructor The new object will contain the values of the previous
object.

Table 2: Confirmation of practice tasks T1, T2

Practice Confirmatio Comments


Tasks n
T1
T2

37. Evaluation Task (Unseen) [Expected time = 55


Mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.

38. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.

Table 3: Evaluation of the Lab

Sr. Task No Description Marks


No.
1 4.1 Problem Modelling 10
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with 30
Testing
4 7.2 Practice task 2 with 20
Testing
5 8 Evaluation Tasks 25
(Unseen)

53
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

6 Good Programming 10
Practices
Total Marks 100

39. Further Reading

39.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

39.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

54
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-05)
Abstraction III
(Shallow Copy / Deep Copy and Working with Arrays)

55
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
582.
Activity Time
boxing 583.
Objective of the
Experiment 584.
Concept
Map 594.1
Creating a customized copy
constructor 594.2
Shallow Copy
Constructor 594.3
Deep Copy
Constructor 604.4
Working with
Arrays 615.
Home Work Before
Lab 635.1
Practices from
Home 646.
Procedure &
Tools 646.1
Tools
646.2
Setting-up Visual Studio
2008 646.3
Walkthrough
Task 647.
Practice
Tasks 657.1
Practice Task
1 667.2
Practice Task
2 667.3
Outcomes
667.4
Testing
668.
Evaluation Task
(Unseen) 679.
Evaluation
Criteria 6710.

56
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Further
Reading 6810.1
Books
6810.2
Slides
68

57
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 05: Deep Copy / Shallow Copy and Arrays in


Classes
40. Introduction
In the previous lab a very basic introduction to copy constructors was presented. The purpose of a copy
constructor is to assist in the creation of exact copy of an object when it is being created. From the
perspective of a beginner this is enough but when we investigate the concept of copying we find that the
default copy constructor is not enough. Hence we need to define our own copy constructor. In this lab the
creation of a copy constructor with details about deep copy and shallow copy will be presented.
Arrays play an important role in any program. Arrays can be used in many forms in OOP for example arrays
as data members, arrays of objects, using static and dynamic arrays and finally the relating arrays and
constructors. All these aspects of arrays will be discussed in detail in this lab.
Relevant Lecture Material
● Lectures: 8, 9, 10

41. Activity Time boxing


Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
5.1 Evaluation of Design 25 mins 25 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 30 mins 30 mins
7 Practice tasks 50 + 15 (mins) 65 mins
8 Evaluation Task 45 mins 45 mins
Total Time 170 Minutes

42. Objective of the Experiment


After completing this lab the student should be able to:
● Understand the difference between a shallow copy and deep copy constructor.
● Explain why a deep copy constructor is needed
● Program a customized copy constructor (both deep and shallow)
● Create an array of objects
● Create and initialize an array of objects.
● Create and use an array as a data member.
● Use both static and dynamic arrays in classes.

58
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

43. Concept Map

43.1 Creating a customized copy constructor


Although C++ provides you with a basic copy constructor, but still there are occasions when you need to design you
own copy constructor. Given below are some of the reasons why you might want to create a copy constructor.
● You need to copy only some of the data members to a new object.
● Your objects contain pointers.
● Your objects contain dynamic data members.
There may be other numerous reasons why you might want to create a customized copy constructor. Before you begin
you must familiarize yourself with the syntax of a copy constructor. A copy constructor always receives an object as
a parameter and hence we can extract the data from the parameterized object and place the data in the newly created
object. Presented below are the two syntax for copy constructors:
MyClass (MyClass& other ); // A copy constructor prototype for a class
called MyClass
MyClass (const MyClass& other ); //const copy constructor prototype for
class called Myclass
In the above prototypes the object which will be copied is called “other”. By writing the const keyword a copy of an
object can be created without any change to the inherent data members. Although only some of the data members can
be copied.

43.2 Shallow Copy Constructor


A shallow copy constructor is a copying function that does a member by member copy of one object to
another. The copy constructor provided by default is a shallow copy constructor. If a class does not have
any dynamic members then only a shallow copy constructor is needed.
Consider another case in which you want to create a partial copy of an object i.e. you only want to copy
some of the static data members then we need the help of a shallow copy constructor.

59
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

In the above code when object obj1 is created the nullary constructor is called and hence values 10 and 20
are allocated to data members a and b respectively. Now when object obj2 is being created obj1 is passed
to the copy constructor as an argument. While creation of obj2 control is never shifted to the basic
constructor because we are attempting to make a new object by copying.

43.3 Deep Copy Constructor


A deep copy constructor is a constructor that has been designed to handle pointers and dynamic data
members. Although a shallow copy constructor will also copy pointers but it does so in an incorrect way.
Hence it is logically wrong to use a shallow copy constructor for dynamic data members.
The problem with shallow copy constructors:
The problem with shallow copy constructors is that suppose you have a class that has a pointer as a data
member and you want to create a copy of this class object. When you call the shallow copy constructor it
will copy the pointer data member to the new object. You might think this is what we want but in fact it is
wrong because copying a pointer means that you have copied the data and the address to which the pointer
is pointing. Hence you have on hand two objects that are pointing to the same memory location. Always
remember that two objects should have their own distinct identity and distinct memory.

60
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Memory
Copy of
Object Object
1 1

(a)
Memory
Copy of
Object Object
1 1

(b)

Figure 1: The effect of copy constructors on a pointer data member (a) using shallow copy (b) Using deep
copy
In the code snippet below a deep copy constructor has been provided that creates a copy of a char array.
The data member len is being used to hold the length of the array.

When working with copy constructors it is important to remember that the copy constructor function
prototype is the same for both shallow copy and deep copy. Hence the difference lies in the fact that dynamic
data members are being handled or not. To determine if a deep copy or shallow copy constructor is being
used you have to study the copy constructor body.

43.4 Working with Arrays


As explained earlier, arrays are of very importance in every program. The main reason for their importance

61
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

is that they provide contiguous memory locations that can be accessed with a simple iterative mechanism
like loops. When it comes to classes we have many options relating to arrays. All the possibilities related
to arrays are part of this lab.
Given below is a class named example that contains a simple (static) floating point array “a”. This array
can be initialized with a constructor or with a simple member function as follows.

class example
{
private:
float a[10]; //array as a data member
public:
example() // normal constructor
{
for(int i=0; i<=9;i++)
{
a[i]=0; // put the value 0 in all
locations
}
}
// other stuff
};
Given below is a class named example that contains a dynamic floating point array “a”. This array can be
initialized with a constructor or with a simple member function as follows. Since this code works with a
dynamic array therefore the size of the array can be provided at run time. In this particular code since the
size is not passed there may be a possibility that the programmer crosses the array boundary.

class example
{
private:
float *a; //Dynamic array as a data member
public:
example() // normal constructor
{
a=new float[10]; //size can be passed from main to
constru

for(int i=0; i<=9;i++)


{
a[i]=0; // put the value 0 in all
locations
Given below is a class named example that contains a dynamic floating point array “a”. This array can be
} member function as follows. Since this code works with a
initialized with a constructor or with a simple
}
dynamic array therefore the size of the array can be provided at run time. In this particular code since the
// other stuff
};
62
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

size is not passed there may be a possibility that the programmer crosses the array boundary.
Another option which is very popular among programmers is that the size of the array can be stored as a
data member.

44. Home Work before Lab


Provided below is a statement for a program which you will code and submit to your lab instructor.

63
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

44.1 Practices from Home


Constructors of a class can be both public and private. Explain why you would create a private constructor.
Create a simple class with a single data member of your choice. Create a private constructor.
In your code demonstrate how a private constructor is called and how the object is created using a private
constructor.
45. Procedure & Tools
45.1 Tools
Visual Studio 2017.

45.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup Visual Studio and make a project named “english”.

45.3 Walkthrough Task [Expected time = 30


mins]
Write a program that creates a class named “english”. The class has a string data member called sentence
and another called size that shows the number of characters of the string. Create a constructor that initializes
the class objects. Also create a copy constructor that copies the data of one object to the other.

45.3.1 Writing Code


In the source file created in the project “english” write the following C++ code:

class english
{
private:
string sentence;
int size;
public:
example()
{
cout<<"Enter your sentence: ";
getline(cin,sentence);
size=9;
size=sentence.length();
}
example (example & tempobj)
{
size = tempobj.size;
sentence=tempobj.sentence;
}
void showall()
{
cout<<"\nSentence: "<<sentence;
cout<<"\nCharacters: "<<size<<"\n";
} };
64
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

int main( )
{
english obj1;
english obj2=obj1;
cout<<"Object one contains data";
obj1.showall();
cout<<"Copied object contains data";
obj2.showall();
return 0;
}

Figure 1: The “english” class demonstrating the use of a constructor and a copy constructor.

45.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.

45.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 2: Final output of “english” class

46. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to

65
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\dataserver\assignments$\OOP\Lab05

46.1 Practice Task 1 [Expected time = 50 mins]


Create a class entertainment consisting of the following data members:
● Title
● Air_Date i.e. Release Date
● Genre
● Type (i.e. Movie, TV Show)
● Runtime
● Country
● Actors
● Rating.
Follow the instructions below for creating the class and objects: Store the owners name as a dynamic array data
member.
● Store the genre as a dynamic array data member.
● Store the names of the actors as a dynamic array data member.
● Create an object named “obj1” and initialize the object.
● Create a copy constructor that can list of genre, country and rating.
● Generate another object named “obj2” that is created by copying only the genre, country and ratings from
“obj1”.
● Initialize the remaining attributes with values of your own.

46.2 Practice Task 2 [Expected time = 15 mins]


Your task is to create a class name polygon that contains 2 data members i.e. length of type float and width
(a pointer of type float). Create a single object named “one” in the main and assign values to the data
member of the polygon object. Then create another object named “two” that is a copy of the “one”. Create
a shallow copy constructor that copies only the pointer data member of the class polygon and then
demonstrate that both objects share a common memory i.e. modifying one object in fact modifies the other.
Create a display function that will show the values of the polygon object.

46.3 Outcomes
After completing this lab, students will be able to conveniently use a copy constructor in both deep copy
and shallow copy mode. Further the students will have the ability to comfortably use arrays in their various
forms both inside and outside the class.

46.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Title = Interstellar After selective copying only the permanent attributes
Air_Date = October 26th,2014 contain values.

66
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Genre = Drama, Mystery Title = Gravity


Type = Movie Air_Date = December 30th,2013
Runtime = 2h 49m Genre = Drama, Mystery
Country = USA Type = Movie
Actors = Matthew MacConaughey, Anne Runtime = 2h 14m
Hathaway, Jessica Chastain, Machenzie, Country = USA
Casey Affleck, Matt Damon Actors = George Clooney, Sandra Bullock, Ed Harris
Rating = 8.6/10 Rating = 8.6/10

Test Cases for Practice Task-2


Sample Inputs Sample Outputs
Initialize only object “one” and use it for Upon calling the display function of object “one” the
copying values into object “two” by using modified values will be displayed
the copy constructor.
Make a modification in object “two”. Upon calling the display function of object “two” the same
Call the display function of object “one”. modified values will be shown.

Table 2: Confirmation of practice tasks T1 and T2

Practice Confirmatio Comments


Tasks n
T1
T2

47. Evaluation Task (Unseen) [Expected time = 45


mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.

48. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.

Table 3: Evaluation of the Lab

Sr. Task No Description Marks


No.
1 4.1 Problem Modelling 10
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with 30

67
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Testing
4 7.2 Practice task 2 with 20
Testing
5 8 Evaluation Tasks 25
(Unseen)
6 Good Programming 10
Practices
Total Marks 100

49. Further Reading

49.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

49.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

68
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object Oriented Programming


(LAB-06)

File Handling in C++

69
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
69

2.Activity Time-
boxing 69

3.Objective of the
Experiment 70

4. Concept
Map 70
4.1 Permanent
Storage 70
4.2 Data
Retrieval 71

5.Home work before


Lab 71
5.1Problem solution
modeling 71
5.2Practices from
home 71

6.Procedure &
Tools 71
6.1 Tools
71
6.2Setting-up Visual Studio 2017
71
6.3Walkthrough Task
71

7. Practice
Tasks 74
7.1Practice Task 1
74
7.2 Out
comes 75
7.3 Testing
75

70
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

8.Evaluation Task (Unseen)


75

9. Evaluation
Criteria 75

10. Further Readings 76


10.1 Slides
76

Appendix A – File Opening Modes 76

71
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 6: File Handling in C++


50. Introduction
This lab will introduce you about how to implement file handling code in C++. The section 2
presents a table that outlines some major activities and tasks you will do as the part of this lab.
Table 1 also provides the estimated-time for each activity, which will help you to organize your
tasks well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept
Map”) discusses and provides a comprehensive introduction of the topic. Section 5 lists the set of
home-tasks you are required to complete before this lab. Section 6 presents a “walkthrough task”
that you will do as the first practical activity during your lab. The walkthrough task has many small
steps which you should follow as directed in-order to complete the task and to get the desired
output. After that, you will be ready to work on some tasks on your own. The section 7 lists practice
tasks for this purpose. As the part of section 8, your lab instructor will give you some tasks at
runtime and will evaluate those according to the criteria mentioned in section 9. Section 10 lists
some further reading links.

Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.

Relevant Lecture Readings:


a) Lecture No. 23
b) Text Book: Computer Programming by D. S. Malik, pages: 147—150

51. Activity Time-boxing

Table 1: Activity Time Boxing


Task Acitivity Name Activity time Total Time
No.

5.1 Evaluation of Design 20 mins 20 mins


6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Specialized Tasks 35 mins 15 mins
7 Practice tasks 30 mins for the task 1 and 40 min 70 mins
for task 2

8 Evaluation Task 30 mins for each assigned task 60 mins


Total Time 170 mins

72
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

52. Objective of the Experiment


● To get basic understanding of writing and reading operation of text files using C++.
● To practice the usage of the ifstream, ofstream and fstream objects.
● Be familiar with basic filing related I/O member functions.

53. Concept Map


A file is a collection of information, stored on a computer’s disk. Information can be saved to
files, and then later read and reused. C++ provides the following classes to perform input/output
operations on the files:
● ofstream: Stream class to write in files
● ifstream: Stream class to read from files
● fstream: Stream class to both read and write from/to files.
These classes (ofstream, ifstream, and fstream) are derived from the classes istream, and
ostream. We have already used objects of these stream classes for example: cin (for standard
input), and cout (for standard output). Similarly, we can use the file streams objects to perform
input (read operation) and output (write operation) in the files. File operations are used extensively
in most of the large projects where we have to save the data permanently on the disks.
You can create an ofstream object to perform writing or output operations on the files while the
ifstream object can only be used for reading from the files. If you want to perform both the writing
and reading operations on the file, please use the fstream objects. Before reading/writing to a file,
it must be opened. To open a file, you can call open function of ofstream, ifstream, or fstream.
void open(const char *filename, ios::openmode mode);
In the above function the first argument specifies the name of the file to open. If the file to open is
not in the current directory (where .cpp files reside) provide complete path with filename. The
second parameter specifies the file opening mode. A list of file opening modes is provided in
Appendix (A).

53.1 Permanent Storage


Usually the data stored in variables is lost when an application exits. If we require using some
calculated data in the program, or need to save the user inputs for the later use (after some time),
then we have to store this data permanently to hard-disk. Filling allow us to write program state to
the hard-disk and further retrievals of the previously saved data.

53.2 Data Retrieval


Some applications needs initial data to run/execute for example: system programs, etc. On startup,
manual input of the initial data every time we launch the application will be very tedious. In this

73
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

situation, filling help us to read data from the permanent storage for example a hard-disk, and
applications can be launched with correct starting state.

54. Home work before Lab

54.1 Problem solution modeling


Write all the steps involved in writing and reading of text file in C++. You need to the
flowchart/steps with you and need to give it to the lab instructor. This will be evaluated and it
carries certain marks as can be seen from the section 9, Table 2.

54.2 Practices from home


Write a C++ program which writes a string “My first file handling program!” on a file named
“first.txt”. The programs also read the written that line (“My first file handling program!”) from
the file named“first.txt” and display it on the screen:

55. Procedure & Tools

55.1 Tools
Visual Studio 2017.

55.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup Visual Studio and make a project named “WordCounter”. For setup details please refer to
the Lab-1 section 6.2.

55.3 Walkthrough Task [Expected time = 35 mins]

55.3.1 Write in a text file using C++.


Your program should take input from user about a student record. A student record means that you
are required to get his name (string type), age (int type), and program (string type). Read data for
all these data-items from the user then write in a text file named “student.txt”.

55.3.2 Writing Code


Write the following code as shown in the Figure 1. This code is for writing student information in

74
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

to the file named “student.txt”.

Figure SEQ Figure \* ARABIC 1: C++ program to write data in a


text file

55.3.3 Compilation
▪ After writing the code, compile your code according to the guidelines
mentioned in Lab-1 (section 6.3.2)

55.3.4 Executing the Program


▪ Execute the above program. After successful execution of the program a
text file named “student.txt” will be created in the current directory (where
your .cpp file resides). You may open the “student.txt” file and examine the

75
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

data written in the file.

Figure SEQ Figure \* ARABIC 2: Contents or values of ▪


the text file "student.txt"

55.3.5 Reading a text file

Read the student information which was written in the previous program example. After reading
the data from “student.txt”, output it to the screen. For reading the file, write following C++ code
(as shown in the Figure 3). This code opens the “student.txt” file for reading student information
and outputs on the screen.

76
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 3: C++ program to read "student.txt" file.

55.3.6 Compilation
▪ After writing the code, compile your code according to the guidelines
mentioned in Lab-1 (section 6.3.2).

55.3.7 Executing the Program


Execute the above program. After successful execution of the program data will be read from the
file and will be displayed on the screen as shown in the figure below:

77
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure SEQ Figure \* ARABIC 4: Output of the read


program.

56. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the folder
specified by your lab instructor.

56.1 Practice Task 1


Write a C++ program which takes 5 students’ information (records) as inputs from the user and
save them on a file. Your program should have two options: writing and searching.

When a user selects writing option, you are required to take three inputs from the user: student
name (string type), student age (int type). After reading these data-items write to the file named
“student.txt”. Please note: write data using append mode otherwise previous information will be
lost.

Your program should have a search function. The search function should provide three options
for searching: by name, by age, or by registration number. After selection of the search option
by the user, please take input (name, age, or registration number) and search that student from the
file and display its record on the screen.

56.2 Practice Task 2


Write a C++ program which takes multiple Employees information (records) as inputs from the
user and save them on a file using class. Writing in file should be done using setters. Perform
following operations on the data saved in the file:
● Read data from file
● Search an employee’s information in the file
● Count the number of employees having salary more than 50,000.

78
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

56.3 Out comes


After completing this lab, student will be able to read and write data in a text file.

56.4 Testing

Test Cases for Practice Task-1


1. Please ensure that the student information being written in the file is actually written or
not. For this, you have to examine by double-clicking the “student.txt” file (in the current
directory) and verify its contents.
2. All recorded student data must be retrievable by search option.

Practice Confirmation
Tasks
T1

57. Evaluation Task (Unseen) [Expected time = 55 mins]


The lab instructor will give you unseen task depending upon the progress of the class.

58. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 2: Evaluation of the Lab


Sr. No. Task Description Marks
No
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1 Practice tasks and Testing 35
4 8.1 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

79
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

59. Further Readings

59.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$

Appendix A – File Opening Modes

File Mode
Meaning
Flag

Append mode.
If the file already exists, its contents are preserved and all output is written to
ios::app
the end of the file. By default, this flag causes the file to be created if it does
not exist.
If the file already exists, the program goes directly to the end of it. Output may be
ios::ate written anywhere in the file.
Binary mode. When a file is opened in binary mode, information is written to or
ios::binary read from it in pure binary format. (The default mode is text.)
If the file does not already exist, this flag will cause the open function to fail. (The
ios::noreplace file will not be created.)

Input mode. Information will be read from the file. If the file does not exist, it
ios::in will not be created and the open function will fail.
If the file does not already exist, this flag will cause the open function to fail. (The
ios::nocreate
file will not be created.)
Output mode. Information will be written to the file. By default, the file’s contents
ios::out will be deleted if it already exists.
If the file already exists, its contents will be deleted (truncated). This is the default
ios::trunc
mode used by ios::out.

80
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-07)
Reusability I
(The protected Access Specifier and Types of Inheritance)

81
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
842.
Activity Time
Boxing 853.
Objective of the
Experiment 854.
Concept
Map 865.
Homework before
Lab 865.1
Problem Solution
Modeling 865.2
Practices from
Home 876.
Procedure &
Tools 886.1
Tools
886.2
Setting-up Visual Studio 2017
886.3
Walkthrough Task
887.
Practice
Tasks 907.1
Practice Task 1
907.2
Practice Task 2
917.3
Practice Task 3
917.4
Outcomes
927.5
Testing
928.
Evaluation Task (Unseen)
929.
Evaluation
Criteria 9210.
Further
Reading 9310.1
Books
9310.2
Slides

82
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

93

83
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 07: The protected Access Specifier and Types of


Inheritance in C++
60. Introduction
So far, you have learned the importance and use of two (public and private) access specifiers within
class(es) of C++. You know that a class’s member functions are able to access class’s data fields
having public or private accessibility for all times. However, externally created object(s) can only
access public data members of that class and private data members are restricted to be accessed
outside the class. For example, consider the following class:

class Examp
{
private:
int attribute;
public:
void show()
{
cout<<attribute;
}
};

Any externally created instance (e.g. Obj) of class Examp would not be able to access data
member(s) directly while using the dot (.) operator. Hence, in the main() function, the statement
Obj.attribute is not legal but the statement Obj.show() is legal.

It is sufficient to know about public and private access specifiers/modifiers in the absence of
inheritance. However, in case of inheritance, sometimes it is required to access data member(s) of
base class in derived class(es) but not outside these classes. In this situation, you must make access
protected for that data member(s) rather than private or public. Protected access will ensure access
of data members only within inheritance hierarchy.

Another important use of access specifiers is their role in the inheritance process. Considering
access specification in C++, inheritance can be private, protected, or public. Each type of
inheritance has specific rules to access base class’s data member(s), which have been explained
below.

Public Inheritance:
Syntax: class Student: public Person
{
};

84
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

If a class is derived from a base class with public specifier, then all public/protected member(s) of
base class become public/protected member(s) of derived class. However, private member(s) of
base class are never accessible from derived class directly.

Protected Inheritance:
Syntax: class Student: protected Person { };

If a class is derived from a base class with protected specifier, then all public/protected member(s)
of base class become protected member(s) of derived class. However, private member(s) of base
class are never accessible from derived class directly.

Private Inheritance:
Syntax: class Student: private Person { };

If a class is derived from a base class with private specifier, then all public/protected member(s)
of base class become private member(s) of derived class.
Relevant Lecture Readings:
● Lectures: 17, 18
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 372 - 428

61. Activity Time Boxing


Table 1: Activity Time Boxing

Task Activity Name Activity time Total Time


No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 25 mins for task 1 and 2 85 mins
35 mins for task 3
8 Evaluation Task 50 min for all assigned 50 mins
task
Total Time 170 mins

62. Objective of the Experiment


After completing this lab, the student should be able to:
● get basic understanding of inheritance in OOP
● develop a derived class from a base class through inheritance

85
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● understand the use of protected access specifier with class’s data members
● understand public, private, and protected types of inheritance

63. Concept Map


Inheritance is one of the most important building blocks of OOP. The concept of reusable classes
is helpful to manage objects. You can create new classes (derived classes) that are able to inherit
certain attributes and behavior of their ancestor or base class(es). Prior to working with inheritance,
it was important to consider that data member(s) should have private access and only through
public member functions, you can access data members of a class. However, with inheritance, it
is sometimes required to have an intermediate level of accessibility to class’s data member(s) that
exists only within inheritance class hierarchy but not outside these classes.

C++ provides intermediate level of accessibility through protected access specifier. Data
member(s) of a base class with protected accessibility are only be directly accessible within base
class and all of its derived classes but not in other parts of the program. Nevertheless, you should
be careful while making data field(s) protected. Use protected access only where you think that
derived classes will use base class data field(s). The access of protected data members in the
derived classes make them less secure than private data members.

Moreover, access specifiers also play their role in the inheritance process. Considering access
specification in C++, inheritance can be private, protected, or public. The effects of access
specifiers in inheritance process on derived class’s member(s) are different as illustrated in Table
2.

Table 2: Inheritance access specifiers and their effect on derived class members

Access Specifier with Inherited class


Private Protected Public
Private Inaccessibl Inaccessibl Inaccessibl
Access Specifier with
e e e
Data Member in Base
Protected private Protected protected
class
Public private Private Private

64. Homework before Lab

64.1 Problem Solution Modeling


Draw UML class diagrams of the following task. You are required to bring this design with
you and submit to your lab instructor.

5.1.1 Problem description:

86
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Design a class named Rectangle that includes


● data members for the length and width of a rectangle,
● respective mutator and accessor functions to set and get values of length and width, and
● a member function named recArea() to compute the area of rectangle (length x width)

From the Rectangle class, derive a class named Cuboid that contains
● a data field named height in addition to length and width,
● two functions named setHeight and getHeight() to set and get value of height data field,
and
● a member function named cuboidArea() to calculate the area of a cuboid (length x width
x height)
Draw UML diagram for each class and show inheritance relationship between these classes.

64.2 Practices from Home


5.2.1 Task-1

Consider a class named GraduateCourse that includes


● Three data members i.e.
o courseID (e.g. CS2133),
o courseName (e.g. OOP),
o creditHours (e.g. 3 or 4), and
o courseFee (e.g. Rs. 10,000).
● A parameterized constructor to initialize data members with values specified by the user

Derive a class named ResearchCourse from Course class, which contains


● An additional data field named experimentFee
● A parameterized constructor to initialize its own data member along with data members
of the base class inherited in derived class
● ResearchCourse class also contains a member function named setExperimentFee to
modify the value of its own data field
● A function named display to show the values of its own attribute along with the attributes
of its base class
● A function named totalFee to display the value of aggregated fee (course fee + experiment
fee) for a particular course object

Implement both classes and in the main() function, create an instance of ResearchCourse class.
Invoke appropriate functions to display all attribute values as well as the total fee for this particular
instance.

5.2.2 Task-2

87
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Representing a point in the plane, a class named PlanePoint has


● Two data members i.e. X and Y (correspond to x and y coordinates) of integer type,
● Two accessor functions named as getX() and getY() to get values of data members X and
Y
● A function named planeDistance() that calculates and returns the distance between two
points in a plane

Derive a class named SpacePoint to imagine a point in a three-dimensional space and has
following additional features:
● A data member Z of type integer to represent the z-coordinate of a point in space
● A no-argument constructor that constructs a point with coordinates (0,0,0)
● A constructor with three arguments that constructs a point with three specified coordinate
values
● An accessor function, which returns the value of data field Z
● A function named spaceDistance to return the distance between two points in the space

Implement both the classes and in the main() create two points with different dimensions and
invoke appropriate function to display the distance between these two points.

65. Procedure & Tools

65.1 Tools

Visual Studio 2017.

65.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]

Setup visual studio and make a project named “InheritanceSpecifier”

65.3 Walkthrough Task [Expected time = 30 mins]

In this task, you are required to write a C++ code which would elaborate protected access specifier
concept. The following lines show the output of basic Inheritance concept with protected data
fields:

6.3.1 Writing Code

In the source file, which is created in the project “InheritanceSpecifier” write following C++ code:

88
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: Base and Derived Classes

Figure 2: Main function for Figure 1

89
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.

6.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible
inputs.

Figure 3: Final Output

66. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab07

66.1 Practice Task 1 [Expected Time = 25 mins]

Create a class Car, which contains


● Three data members i.e. carName (of string type), ignition (of bool type), and
currentSpeed (of integer type)
● A no-argument constructor to initialize all data members with default values
● A parameterized constructor to initialize all data members with user-defined values
● Three setter functions to set values for all data members individually
● Three getter function to get value of all data members individually
● A member function setSpeed( ) // takes integer argument for setting speed

Derive a class named Convertible that contains


● A data member top (of Boolean type)
● A no-argument constructor to assign default value as “false” to top
● A four argument constructor to assign values to all data-members i.e. carName, ignition,
currentSpeed and top.

90
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● A setter to set the top data member up


● A function named show() that displays all data member values of invoking object

Write a main() function that instantiates objects of Convertible class and test the functionality of
all its member functions.

66.2 Practice Task 2 [Expected Time = 25 mins]


Company is the base class that holds
● Data fields named companyID (of integer type), and companyName (of string type).
● A two-argument constructor to initialize data-fields with user-defined values
● Appropriate accessor and mutator functions to set and get values of data fields

Derive two classes from the Company class:


● MobilePhone, which contains an attribute mobiulePhoneName of string type, mobileID
of integer type, mobilePrice of integer type and setters and getters member function of all
data members
● Laptop which contains an string variable named laptopName along with a member
function to set laptop name
● Both derived classes have function display to show all data field values (including values
inherited from the base class).

In the main() function, create objects of MobilePhone and Laptop classes and show the advantages
of using protected access specifier.

66.3 Practice Task 3 [Expected Time = 35 mins]

A class named CafeService contains


● Two data members i.e. the orderID and the price of food item(s) served by
● A no-argument constructor to initialize both data fields with default values of “ord#0”,
0.0
● A parameterized constructor to initialize all data fields with user-defined values

Derive a class named StaffService from the class CafeService that holds the following:
● Two data members i.e.
o serviceFee,
o the cabinNumber to which the service has been made

● A function named totalCharges that returns total cost of an order (including serviceFee +
price of food item(s) served)
● A parameterized constructor, which requires arguments for all of its own data fields as

91
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

well as for the data fields of base class


● A member function named display() to show all the details of an order including orderID,
price, and totalCharges

In the main() function, instantiate an object of class StaffService object and test the
implementation of both classes through this object.

66.4 Outcomes
After completing this lab, student will be able to understand the implementation and design of
inheritance as well as the use of protected access specifier in inheriting classes.

66.5 Testing

For all Practice Tasks, lab instructor must examine the implementation of all mentioned classes
the creation of instances of specified classes the invocation of specified functions

Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation Comments


T1
T2
T3

67. Evaluation Task (Unseen) [Expected Time = 50 mins for all tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

68. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 4: Evaluation of the Lab

Sr. No. Task No Description Marks


1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks (Unseen) 20
4 Comments 5
5 Good Programming 10

92
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Practices
Total Marks 100

69. Further Reading

69.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

69.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

93
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-08)
Multi-level and Multiple Inheritance

94
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
962.
Activity Time
Boxing 973.
Objective of the
Experiment 974.
Concept
Map 985.
Homework before
Lab 985.1
Problem Solution
Modeling 985.2
Practices from
home 996.
Procedure &
Tools 1006.1
Tools
1006.2
Setting-up Visual Studio 2017
1006.3
Walkthrough Task
1007.
Practice
Tasks 1027.1
Practice Task 1
1027.2
Outcomes
1047.3
Testing
1048.
Evaluation Task (Unseen)
1059.
Evaluation
Criteria10510. Further
Reading 10510.1
Books
10510.2
Slides
105

95
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 8: Multi-level and Multiple Inheritance


70. Introduction
In the previous labs i.e. in [Lab 06] and [Lab 07], you have already learned that the inheritance in
object-oriented programming (OOP) is the ability to transfer attributes and behaviors from
base/parent class(es) to derive/child class(es). As a next step, it is essential to learn the types of
inheritance on the basis of class hierarchies. Following different class hierarchies, inheritance in
OOP can be categorized as

● Single Inheritance: a single child class derived from a single base class
● Hierarchical Inheritance: multiple child classes derived from a single base class
● Multi-level Inheritance: a single derived class inherited from another derived class
● Multiple Inheritance: a single derived class inherited from more than one base classes
● Hybrid Inheritance: any legal combination of more than one type of inheritance

In particular, the main focus of this lab is concerned with the understanding of multi-level and
multiple inheritance. Multi-level represents the scenario of inheriting attributes and behavior of a
class that is already inheriting attributes and behaviors from other class(es). The syntax of writing
C++ code to implement multi-level class hierarchy is given as under:

class X
{
// code statements go here
};
class Y: public X
{
//code statements go here
};
class Z: public Y
{
//code statements go here
};
...

There is no limitation on the number of levels in multi-level inheritance.

Multiple Inheritance represents where a single class inherits attributes and behaviors from more
than one class. The syntax to write C++ code for multiple inheritance is given as under:

class X

96
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

{
// code statements go here
};
class Y
{
//code statements go here
};
class Z: public X, public Y
{
//code statements go here
};

Relevant Lecture Readings:


● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 399- 412

71. Activity Time Boxing


Table 1: Activity Time Boxing

Task Activity Name Activity time Total Time


No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 80 mins 80 mins
8 Evaluation Task 55 min for all assigned 55 mins
task
Total Time 170 mins

72. Objective of the Experiment


After completing this lab, the student should be able to:
● develop multiple level class hierarchies
● derive a child class from multiple base classes
● understand the advantages of multi-level inheritance and multiple inheritance

97
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

73. Concept Map


Inheritance is one of the most important building blocks of OOP. The concept of reusable classes
is helpful to manage objects because occasionally it happens that a class may have some features
that it can derive from already existing class(es). Hence, with inheritance, it is sometimes crucial
to build multi-level class hierarchies or to derive class(es) from multiple existing classes. To grasp
the concept and need of multi-level and multiple inheritance, consider the following class
hierarchy

Figure 1: Class Hierarchies showing Multi-level and Multiple Inheritance

A person can be an employee or a student. An employee may have rights of admin officer or of
academic officer. These class hierarchies represent multi-level inheritance. However, a Dean or
Head of Department (HOD) may have rights to modify the status already defined by an admin or
academic officer. This type of relationship between classes is an example of multiple inheritance.

C++ facilitates users while supporting the implementation of both multi-level and multiple
inheritance. There is no limitation on the number of levels in multi-level inheritance and there is
no limitation on the number of parent classes from which a child can be derived. Nevertheless, as
a good practice, it is recommended to restrict levels and number of base classes to two in multi-
level and multiple inheritance.

74. Homework before Lab

74.1 Problem Solution Modeling


Draw UML class diagrams of the following task. You are required to bring this design with
you and submit to your lab instructor.

5.1.1 Problem description:


98
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Design a class named Staff that includes


● A data member named staffID
● A parameterized constructor to initialize staffID
● A getter function to get the value of staffID
Derive a class named Professor inherited from Staff class and contains
● Two additional data members i.e. departmentID and departmentName
● A parameterized constructor to initialize its own data fields along with the inherited data
field
● Two getter functions that return the departmentID and departmentName, respectively
Derive a class named VisitingProfessor inherited from class Professor and has
● A data field named no_of_courses
● A data field named salary_per_course
● A function named totalSalary that returns total payment for all courses (i.e. no_of_courses
* salary_per_course)
● A member function named display to show total salary of visiting professor

Draw UML diagram for each class and show inheritance relationship between these classes.

74.2 Practices from home


5.2.1 Task-1

Consider the problem description of section 5.1.1 of this lab that deals with three classes i.e. Staff,
Professor, and VisitingProfessor. Implement all these classes and in the main function, create an
object of class VisitingProfessor and invoke its member function display to show total income of
a visiting professor.

5.2.2 Task-2

Consider four classes named Animal, Mammal, Bird, and Bat.


● class Animal that includes the functionality of eating and breathing
● class Mammal derived from Animal class and has additional functionality of giving birth
but not hatching
● class Bird derived from Animal class and has specific functionality of flying
● class Bat derived from both Animal and Bird classes while inheriting the functionality of
both these classes

Draw UML diagram for each class and show inheritance relationship between these classes.
Moreover, illustrate the implementation of these classes in C++.

99
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

75. Procedure & Tools


75.1 Tools
Visual Studio 2017.

75.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup visual studio and make a project named “MultipleInheritance”

75.3 Walkthrough Task [Expected time = 30 mins]


In this task, you are required to write a C++ code which would elaborate multiple-inheritance
concept. The following lines show the output of a basic multiple-inheritance concept:

6.3.1 Writing Code

In the source file, which is created in the project “MultipleInheritance” write following C++ code:

#include<iostream>
using namespace std;

class Student
{
protected:
int registrationNum,marks1,marks2;
public:
void getMarks()
{
cout<<"Enter the Registration number: ";
cin>>registrationNum;
cout<<"Enter the marks: ";
cin>>marks1;
cin>>marks2;
}
};
class SportActivity
{
protected:
int sportsmarks;
public:
void getSportsMarks()
{
cout<<"\nEnter the marks for sports: ";

100
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

cin>>sportsmarks;

}
};
class MarksStatment:public Student,public SportActivity
{
int totalMarks,averageMarks;
public:
void ShowStatement()
{
totalMarks=(marks1+marks2+sportsmarks);
averageMarks=totalMarks/3;
cout<<"\ntRegistrattion Number: "<<registrationNum<<"\nTotal marks: "
<<totalMarks;
cout<<"\nAvergae marks : "<<averageMarks;
}

};

Figure 1: Multiple Inheritance

Figure 2: Main function for Figure 1

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.

6.3.3 Executing the Program


A sample output after running the program is shown below:

101
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 3: Final Output

76. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab8

76.1 Practice Task 1 [Expected Time =


80 mins]
Consider the following details of all classes for class hierarchy shown in Figure 1 of this lab.

● Class Person holds


o Two attributes i.e. name and year_of_birth
o A two-argument constructor to initialize its data members with user-defined values

● Class Employee contains


o Five attributes i.e. employeeID, joiningYear, jobTitle (designation of an employee),
courseID, and courseTitle

● Class Administration has


o A parameterized constructor to receive five arguments to initialize inherited attributes
from class Employee
(Concerning courseID and courseTitle, only null value is allowed to set for an admin
officer)

102
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

o Two functions i.e. setJobTitle(employee) and getJobTitle(employee) to set and get job
title of an employee.
● Class Student has
o Two attributes i.e. studentID and enrolledSemester
o A four-argument constructor to initialize its data members (including inherited data
members)
o A function named display() to show the values of all attributes (including inherited
attributes)

● Class Academic has


o A parameterized constructor to receive five arguments to initialize inherited attributes
from class Employee
(Concerning employeeID, joiningYear, and jobTitle, only null value is allowed to set)
o Two functions i.e. setCourseID() and setCourseTitle()

● Only an instance of class DeanHOD should be able to modify values for employeeID,
designation of an employee, ID and name of a particular course.

Implement all these classes and within the main function, create instances of all classes (except
class Employee) and test the described working of all these classes.

76.2 Practice Task 2


Consider a base class named Employee and its derived classes HourlyEmployee and
PermanentEmployee while taking into account the following criteria.
● Employee class has two data fields i.e. a name (of type string) and specific empID (of type
integer)
● Both classes (HourlyEmployee and PermanentEmployee) have an attribute named
hourlyIncome
● Both classes (HourlyEmployee and PermanentEmployee) have three-argument
constructor to initialize the hourlyIncome as well as data fields of the base class
● Class HourlyEmployee has a function named calculate_the_hourly_income to calculate
the income of an employee for the actual number of hours he or she worked. One hour
income is Rs. 150
● Similarly, PermanentEmployee class has function named calculate_the_income to
calculate the income of an employee that gets paid the salary for exact 240 hours, no matter
how many actual hours he or she worked. Again, one hour salary is Rs. 150.

Implement all class definitions with their respective constructors to initialize all data members
and functions to compute the total income of an employee. In the main() function, create an
instance of both classes (i.e. HourlyEmployee and PermanentEmployee) and test the working of

103
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

functions that calculate total income of an employee.

76.3 Practice Task 3


Consider a class BankAccount that has
● Two attributes i.e. accountID and balance and
● A function named balanceInquiry() to get information about the current amount in the
account

Derive two classes from the BankAccount class i.e. CurrentAccount and the SavingsAccount.
Both classes (CurrentAccount and SavingsAccount) inherit all attributes/behaviors from the
BankAccount class. In addition, followings are required to be the part of both classes
● Appropriate constructors to initialize data fields of base class
● A function named amountWithdrawn(amount) to withdraw certain amount while taken
into account the following conditions
o While withdrawing from current account, the minimum balance should not
decrease Rs. 5000
o While withdrawing from savings account, the minimum balance should not
decrease Rs. 10,000
● amountDeposit(amount) to deposit amount in the account

In the main() function, create instances of derived classes (i.e. CurrentAccount and
SavingsAccount) and invoke their respective functions to test their working.

76.4 Outcomes
After completing this lab, student will be able to understand the implementation and design of
Multi-level and Multiple Inheritance in C++.

76.5 Testing
● For Practice Task 1, while inspecting implementation of classes, lab instructor must ensure
that student has taken hold the concept of multi-level and multiple inheritance.
Furthermore, it is required to check the invocation of all functions with the created
instances of all mentioned classes.

Table 3: Practice Tasks Confirmation

Practice Confirmation Comments


Tasks
T1

104
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

77. Evaluation Task (Unseen) [Expected Time = 55 mins for all tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

78. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 4: Evaluation of the Lab

Sr. No. Task Description Marks


No
1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks 20
(Unseen)
4 Comments 5
5 Good Programming 10
Practices
Total Marks 100

79. Further Reading

79.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

79.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

105
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-09)
Reusability III
Function Overloading and Function Overriding

106
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
1082.
Activity Time
Boxing 1093.
Objective of the
Experiment 1094.
Concept
Map 1095.
Homework before
Lab 1105.1
Problem Solution
Modeling 1105.2
Practices from
home 1116.
Procedure &
Tools 1116.1
Tools
1116.2
Setting-up Visual Studio 2017
1116.3
Walkthrough Task
1127.
Practice
Tasks 1147.1
Practice Task 1
1147.2
Practice Task 2
1147.3
Outcomes
1157.4
Testing
1158.
Evaluation Task (Unseen)
1169.
Evaluation
Criteria 11610.
Further
Reading 11610.1
Books
11610.2
Slides
116

107
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 9: Function Overloading and Function Overriding


80. Introduction
Earlier in Lab-08, you have already studied that a sub/derived class is able to access all non-private
data members and member functions of the base/parent class. Moreover, besides inheriting
attributes and behaviors from base class(es), the derived class also contains its own data members
and member functions.

Function overloading is the availability of various functions within a class that differ from each
other in function signature i.e. various functions share same name with different parameter types
or number of parameters. Inheritance is not necessarily required to overload functions within a
program.

On the other hand, in function overriding, there must exists inheritance relationship between
classes (i.e. base and derived) and functions’ signature are also required to be same in both parent
and child class(es). However, derived class(es) redefine function(s) having signature similar to
base class’s function(s).

Following code provides an example where both concepts (function overloading and overriding)
have been elaborated:

class Base
{
protected:
void myFunc()
{
cout<<"Base Class’ Function";
}
};

class Derived: public Base


{
public:
void myFunc()
{
cout<<"Derived Class’ Function";
}
void myFunc(int a)
{
cout<<"Derived Class’ Function with Parameter Value" <<a;

108
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

}
};

In the given example (above),


● At first, the class Derived shows function overloading while containing two functions differ
from each other in function signature (i.e. functions myFunc() and myFunc(int))
● Secondly, it also shows function overriding as it holds two function implementations with
same signature (i.e. besides myFunc() of its own, it also contains myFunc() inherited from
the Base class.
Relevant Lecture Readings:
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 188-193, 382-392

81. Activity Time Boxing


Table 1: Activity Time Boxing

Task Activity Name Activity time Total Time


No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 50 mins for task 1 80 mins
30 mins for task 2
8 Evaluation Task 55 min for all assigned 55 mins
task
Total Time 170 mins

82. Objective of the Experiment


After completing this lab, the student should be able to:
● Understand function overloading within a class
● Understand function overriding concerning inheritance class hierarchy
● Differentiate between function overloading and function redefining

83. Concept Map


Function overloading and function overriding are the two key concepts of a number of modern
computer programming languages.

109
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Overloaded functions provide specific functionalities while taking into account the type/number
of parameter(s) they receive and the fundamental advantage is the cleanliness of code. For
example, in the absence of overloading, a computer program may have several functions with
different names to calculate the area of a geometric shape as shown below:

class GeometricShape{
public:
int squareArea(int sideLength);
int reactangleArea(int length, int width);
int triangleArea(int side1, int side2, int side3);
};

However, the same code with function overloading would be as

class GeometricShape{
public:
int area(int sideLength);
int area(int length, int width);
int area(int side1, int side2, int side3);
};

On the other hand, function overriding is the ability of redefining a specific behavior (function) of
a base class within derived class(es). Besides the provisioning of a specific modified
implementation of a base class function, function overriding is used to perform runtime
polymorphism.

84. Homework before Lab

84.1 Problem Solution Modeling


Draw UML class diagrams of the following task. You are required to bring this design with
you and submit to your lab instructor.

5.1.1 Problem description:

Design a class named Automobile that includes


● A data member named currentSpeed
● A setCurrentSpeed function to set currentSpeed of an automobile
● A getCurrentSpeed function to get currentSpeed of an automobile

Derive a class named Car inherited from Automobile class and contains

110
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● An additional data member named color


● A parameterized constructor to initialize its own data fields along with the inherited data
field
● Two functions named setColor and getColor to set and get the color of a Car object,
respectively

Derive a class named Limousine inherited from class Car and has its own functions (i.e.
setCurrentSpeed, getCurrentSpeed, setColor and getColor) to set/get speed and color for each of
its specific instance

Draw UML diagram for each class and show inheritance relationship between these classes.

84.2 Practices from home


5.2.1 Task-1
Consider a class named Calculator with typical four specific functionalities i.e. addition,
subtraction, multiplication, and division. Implement these functionalities as four functions with
two parameters. It is also required to overload all these functions for int and double data types. In
the main function, create an object of class Calculator and invoke its member functions while
passing parameters of int and double type.

5.2.2 Task-2

Consider a class named Animal having typical function named eat that accepts a parameter of type
string. Three classes i.e. Herbivore, Carnivore, and Omnivore have been inherited from Animal
class. All these classes i.e. Herbivore, Carnivore, and Omnivore must have their own (overridden)
eat function.

a) Draw UML diagram for each class and show inheritance relationship between these
classes.
b) Implement all these classes
c) In the main function, create instances of Herbivore, Carnivore, and Omnivore classes and
invoke eat function with appropriate string parameter to display the liking of that animal
in eating.

85. Procedure & Tools


85.1 Tools
Visual Studio 2017.

85.2 Setting-up Visual Studio 2017 [Expected time = 05 mins]


Setup visual studio and make a project named “FunctionOverloading”

111
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

85.3 Walkthrough Task [Expected time = 30 mins]

In this task, you are required to write a C++ code which would elaborate function overloading.
The following lines show the output of a basic function overloading concept:

6.3.1 Writing Code

In the source file, which is created in the project “FunctionOverloading” write following C++
code:

Figure 1: Function Overloading

112
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 2: Main( ) function for Figure 1

113
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.

6.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 3: Final Output

86. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab09

86.1 Practice Task 1 [Expected Time = 30 mins]


● Consider a class Shapethat contains
o A data member named as ShapeName of string type
o A data member named as areaof type int
o A member function displayarea()
● Derive two classes named Circle and polygon from the class Shape that contain
o A parameterized constructor to initialize data members that they inherit from the class
Shape

In the main(), create instances of Shape Circle and Polygon classes. Invoke displayarea() with
shape object while passing references of Circle and Polygon instances.

86.2 Practice Task 2 [Expected Time = 50 mins]


Create a class named Laboratory containing
● Two data fields i.e. name (a string) and location (string)
● A no-argument constructor to initialize all data fields with default values “NoName” and
“NULL”

114
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● A member function named input()


● A member function named show() to display the details associated with an instance of this
class
Derive a class named WetLab from class Laboratory that includes
● data members no_of_microscopes and Scientist_name,
● respective mutator and accessor functions
● overriding function named input() to take input from user in all data members
● overriding function named show() to display the details associated with an instance of class
WetLab

From the Laboratory class, derive a class named DryLab that contains
● a data field named no_of_computers and Capacity
● Setters and getters
● an overriding function named input()
● overriding function named show() to display the details associated with an instance of this
class

Implement these classes and in the main() create instances of each class and test the functionality
of overridden member functions with these instances.

86.3 Outcomes
After completing this lab, student will be able to understand the difference between function
overloading and function overriding within a class or class hierarchies.

86.4 Testing
● For Practice Task 1, lab instructor must confirm the implementation of classes i.e.
GeometricShape, Rectangle, and Cuboid. With instances of each class, test the invocation
of proper overridden function.

● For Practice Task 2, lab instructor ensures the invocation of displayPrice() function with
the MusicalInstrument instance while receiving references of the instances of Flute and
Guitar classes.

Table 3: Practice Tasks Confirmation

Practice Confirmation Comments


Tasks
T1
T2

115
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

87. Evaluation Task (Unseen) [Expected Time = 55 mins for all


tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

88. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
Table 4: Evaluation of the Lab

Sr. No. Task Description Marks


No
1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks 20
(Unseen)
4 Comments 5
5 Good Programming 10
Practices
Total Marks 100

89. Further Reading

89.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

89.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

116
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-10)
Reusability IV
Polymorphism in Object Oriented Programming

117
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
1202.
Activity Time
Boxing 1223.
Objective of the
Experiment 1234.
Concept
Map 1235.
Homework before
Lab 1235.1
Problem Solution
Modeling 1235.2
Practices from
home 1246.
Procedure &
Tools 1256.1
Tools
1256.2
Setting-up Visual Studio 2017
1256.3
Walkthrough Task
1257.
Practice
Tasks 1277.1
Practice Task 1
1277.2
Practice Task 2
1287.3
Practice Task 3
1287.4
Outcomes
1297.5
Testing
1298.
Evaluation Task (Unseen)
1299.
Evaluation
Criteria 12910.
Further
Reading 13010.1
Books
13010.2
Slides

118
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

130

119
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 10: Polymorphism in Object Oriented


Programming
90. Introduction
In general, polymorphism means ‘various shapes’ and within the context of an object-oriented
programming (OOP) language, it is the ability of an object to acquire various forms while
referencing various instances of the different classes in inheritance hierarchy. In OOP, a significant
characteristic is the type compatibility of a derived class pointer to its base class pointer. Taking
advantage of this useful aspect, polymorphism establishes a new way of programming.

To realize polymorphism in C++, you need


● A virtual function and
● A pointer of base class type

A member function of a base class can be made a virtual function if it is probable to redefine
(override) this function in the derived class. The significance of making a function virtual becomes
evident when you want to invoke function of derived class from a pointer of base class referencing
derived class’s object. Following code provides an example of polymorphism mechanism in C++.

class Base
{
public:
virtual void func()
{
cout<<”Base Class Function”;
}
};

class Derived: public Base


{
public:
void func()
{
cout<<”Derived Class Function”;
}
};
void main()
{
Base *bPtr;
Derived dev;

120
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

bPtr = &dev;
bPtr->func();
}

Upon calling func() with bPtr, Derived class func() will be invoked and output would be “Derived
Class Function”. In the absence of virtual keyword, func() of base would be called each time.
Hence, it can be concluded that virtual keyword allow a pointer of base class to call appropriate
function of any of its derived class to whom it is referencing. In this way, each time a different
function will be invoked with the same function call. With polymorphism, compiler does not know
which function to call at compile and thus appropriate function call is deferred to runtime. At
runtime, the type of object that a base class pointer is pointing is recognized to call proper function.
This is known as dynamic or late binding.

Virtual keyword can also be used with destructors and classes. However, virtual keyword
possesses different meanings when used with destructor and classes as explained below.
Virtual Destructors:
In practice, it is always recommended to make the base class destructor as virtual. In the absence
of virtual keyword with base class destructor, upon deletion of any derived class’s object only
destructor of base class would be called.

Virtual Base Classes:


Virtual base classes can be used to avoid diamond problem of multiple inheritance that is explained
as under.

class Base
{
protected:
void func()
{ cout<<”A Base Class Function”; }
};
class Derived1: public Base{ };
class Derived2: public Base{ };
class Derived3: public Derived1, public Derived2
{ };

In the code above, both (Derived1 and Derived2) classes contain a copy of func(), which is
inherited from class Base. Upon the invocation of func() with an object of Derived3 class,
compiler would be unable to decide which copy to use.

To overcome this situation, it is required to use virtual keyword with base class inheritance. Hence,
the above code would be implemented as

121
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

class Base
{
protected:
void func()
{ cout<<”A Base Class Function”; }
};
class Derived1: virtual public Base{ };
class Derived2: virtual public Base{ };
class Derived3: public Derived1, public Derived2
{ };

Pure Virtual Function and Abstract Class:


You may have observed that with any class hierarchy in OOP, derived class(es) become more
specific version of base class(es) which are more general or abstract. It is sometime good in
practice to make the base class as abstract class that contains only the most common features of
all of its derived classes. In C++, you can make base class an abstract class by declaring a pure
virtual function in it. The syntax is given as under:

class Base
{
protected:
virtual void func() = 0;
};

Instantiation of an abstract class is not possible and you should override pure virtual function in
derived class(es).

Relevant Lecture Readings:


● Lectures: 23, 24, 25, 26
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 503- 520

91. Activity Time Boxing


Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 20 mins

122
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

7 Practice tasks 90 mins for three task 90 mins


8 Evaluation Task 55 min for all assigned 55 mins
task
Total Time 170 mins

92. Objective of the Experiment


After completing this lab, the student should be able to:
● Distinguish between static binding and dynamic binding
● Understand polymorphism and dynamic binding while using virtual functions
● Declare abstract classes with pure virtual function

93. Concept Map


Following encapsulation and inheritance, polymorphism is the third important capability of OOP
paradigm. The fundamental inspiration behind polymorphism is that of dynamic binding. In this
way, at compile time, compiler knows nothing about which function to call. On the contrary,
decision is made at runtime. Polymorphism helps programmer to make program in general rather
than specific. In simple words, it provides a single interface with different implementations.
Moreover, polymorphism facilitates program extensibility while permitting new derived classes
and functions to be added to an inheritance hierarchy without modifying application programs that
already utilize various interfaces of that inheritance hierarchy. However, for beginners, it is
difficult to grasp and implement the concept of polymorphism, dynamic binding, and abstract
classes.

94. Homework before Lab

94.1 Problem Solution Modeling


Draw UML class diagrams of the following task. You are required to bring this design with
you and submit to your lab instructor.

5.1.1 Problem description:

Design a class named Record that includes


● A data member named rollNo for student roll number
● Two data fields i.e. course1Name and course2Name of type string
● A parameterized constructor to initialize rollNo, course1Name, and course2Name data
fields
● Three getter functions to get the value of rollNo, course1Name, and course2Name,
respectively

Derive a class named CourseRecord inherited from Record class and contains

123
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● Two additional data members i.e. marksCourse1 and marksCourse2


● A parameterized constructor to initialize its own data fields along with the inherited data
fields
● Two getter functions that return the value of marksCourse1 and marksCourse2,
respectively

Derive a class named CourseResult inherited from class CourseRecord and has
● A data field named totalMarks
● A function named marksObtained that returns totalMarks (i.e. marksCourse1 +
marksCourse2) of a student
● A member function named display to show rollNo, course1Name, course2Name,
marksCourse1, marksCourse2, and totalMarks

Draw UML diagram for each class and show inheritance relationship between these classes.

94.2 Practices from home

5.2.1 Task-1

Consider four classes i.e. Person, Staff, Professor, and Researcher with the following inheritance
hierarchy:

Class Researcher is derived from both Staff and Professor classes that are ultimately derived from
class Person.

Class Person has two attributes i.e. name and age and one member function display() to show its
attribute values.

Class Staff has two attributes i.e. staffID and department.

Class Professor has two attributes i.e. courseID and courseName for the course he/she is teaching.

Class Researcher has additional attributes named labID and experimentNo for laboratory and
experiment under his supervision.

Draw UML diagram for each class and show inheritance relationship between these classes.

5.2.2 Task-2

Illustrate the implementation of classes that have been specified in Task-1 using C++ compiler in

124
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

a way that avoid diamond problem of multiple inheritance.

95. Procedure & Tools

95.1 Tools

Visual Studio 2017.

95.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]

Setup visual studio and make a project named “Polymorphism”

95.3 Walkthrough Task [Expected time = 30 mins]

In this task, you are required to write a C++ code which would elaborate polymorphism concept.
The following lines show the output of a basic polymorphism concept:

6.3.1 Writing Code

In the source file, which is created in the project “Polymorphism” write following C++ code:

125
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: Polymorphism

126
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

6.3.2. Compilation

After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.

6.3.3. Executing the Program

A sample output after running the program is shown below:

Figure 3: Final Output

96. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab10

96.1 Practice Task 1 [Expected Time = 40 mins]


Consider an abstract class Animal having
● A datamember “Name”
● A datamember “Zoo”
● A single function named show()

A class named Birds inherits Animal class and adds fields representing
● A bool type variable flying
● Override function named show() to display values of its all attributes

A class named Reptiles inherits BOOK class and adds fields representing
● Length
● Override function named show() to display values of its all attributes

127
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Write a main() function that instantiates objects of derived classes to access respective show()
function using dynamic binding.

96.2 Practice Task 2 [Expected Time = 40 mins]


Create a class named Person, which contains
● A pure virtual function named print()
● Two data fields i.e. personName and age
A class named Student inherits Person class, which contains
● Two data fields i.e. Std_id and Cgpa
● Overridden function print() to display all details relevant to a patient

A class named Regular inherited from class Student which holds


● A data field representing the name of School
● A data filed representing the Fee
● Overridden function print() to display all details relevant to a Regular student
A class named Private inherited from class Student which holds
● A data field representing the address
● A data filed representing the Fee
● Overridden function print() to display all details relevant to a private Student

In the main function, create instances of derived classes to access respective print() function using
dynamic binding.

96.3 Practice Task 3 [Expected Time = 40 mins]

Create a class named GeometricShape containing


● A pure virtual function named show() is create in the GeometricShape class

Derive a class named Rectangle from class GeometricShape that includes


● data members for the length and width of a rectangle,
● respective mutator and accessor functions to set and get values of length and width, and
● overriding function named computeArea() to compute the area of rectangle (length x
width)
● overriding function named show() to display the details associated with an instance of class
Rectangle

From the Rectangle class, derive a class named Cuboid that contains

128
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● a data field named height in addition to length and width,


● two functions named setHeight and getHeight() to set and get value of height data field,
and
● an overriding function named computeArea() to calculate the area of a cuboid (length x
width x height)
● overriding function named show() to display the details associated with an instance of class
Cuboid

In the main function, create instances of derived classes to access respective show() function using
dynamic binding.

96.4 Outcomes
After completing this lab, student will be able to implement the concepts of virtual functions,
dynamic binding, pure virtual function, and abstract classes.

96.5 Testing
● For Practice Task 1, it is required to check the assignment of derived class instances to
base class pointer. Moreover, (while considering the dynamic binding) test the invocation
of respective show() function.

● For Practice Task 2, it is required to check the assignment of derived class instances to
base class pointer. Moreover, (while considering the dynamic binding) test the invocation
of respective print() function.

Table 3: Practice Tasks Confirmation

Practice Confirmation Comments


Tasks
T1
T2
T3

97. Evaluation Task (Unseen) [Expected Time = 55 mins for all


tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

98. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether

129
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

the student has finished the complete/partial task(s).

Table 4: Evaluation of the Lab

Sr. No. Task Description Marks


No
1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks 20
(Unseen)
4 Comments 5
5 Good Programming 10
Practices
Total Marks 100

99. Further Reading

99.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

99.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lecures$\

130
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-11)
Reusability V
Relationships in Object Oriented Programming

131
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
1332.
Activity Time
Boxing 1343.
Objective of the
Experiment 1344.
Concept
Map 1345.
Homework before
Lab 1355.1
Problem Solution
Modeling 1355.2
Practices from
home 1356.
Procedure &
Tools 1366.1
Tools
1366.2
Setting-up Visual Studio 2017
1366.3
Walkthrough Task
1367.
Practice
Tasks 1387.1
Practice Task 1
1387.2
Practice Task 2
1397.3
Outcomes
1397.4
Testing
1398.
Evaluation Task (Unseen)
1399.
Evaluation
Criteria 14010.
Further
Reading 14010.1
Books
14010.2
Slides
140

132
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 11: Relationships in Object Oriented


Programming
100. Introduction
In OOP, various kinds of relationships (i.e. inheritance, association, aggregation, composition) exist
between various classes/objects.

Inheritance is modeled as is-a relationship. Inheritance exists between classes and the main goal of
inheritance is to make objects that would represent specialized versions of generalized original objects. For
example, a car is-a vehicle, manager is-an employee etc.

On the other hand, association and aggregation/composition represent uses-a and has-a relationship,
respectively between objects. It is based on the object-oriented design where an object can contain other
object(s). Association specifies that objects of different kinds are connected with each other and there exist
no ownership and lifecycle dependency. In advance, aggregation and composition are two types of
association representing weak and strong (whole-part) relationship between contained (whole) and owing
(part) objects. Therefore, aggregation and composition are other forms of code reusability along with
inheritance. Aggregation is a special kind of association represents ownership relationship between objects.
Composition is special kind of aggregation which represents ownership between objects along with the
existence of life-cycle dependency. A department-employees relationship is an example of aggregation
whereas university-departments relationship is an example of composition.

Following example explains the syntax for aggregation and composition in C++:

class Battery{ };
class Engine{ };
class Vehicle
{
private:
Battery *bat;
Engine *eng;
public:
Vehicle(Battery *b)
{
bat = b;
eng = new Engine();
}
~Vehicle()
{
delete eng;
}
};

133
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Above example shows that aggregation exists between battery and vehicle because of the possession of
ownership but not life-cycle dependency. On the contrary, composition exists between vehicle and engine
because of the possession of ownership and life-cycle dependency.
Relevant Lecture Readings:
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 414- 420

101. Activity Time Boxing


Table 1: Activity Time Boxing

Task Activity Name Activity time Total Time


No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 80 mins for assigned task 80 mins
8 Evaluation Task 55 min for all assigned 55 mins
task
Total Time 170 mins

102. Objective of the Experiment


After completing this lab, the student should be able to:
● model relationship between existing classes
● distinguish between association, aggregation, and composition
● understand difference between aggregation and composition in terms of ownership and life cycle

103. Concept Map


Primarily two tasks are the part of each object-oriented design i.e. identification of object types within the
problem domain and relationship modeling between the existing object types. Three kinds of relationships
are usually exist between identified objects i.e.

● is-a relationship (Inheritance)


● uses-a relationship (Association)
● has-a relationship (Aggregation, Composition)

The is-a relationship exhibits a relationship between an object of specific type to its general type. For
example, a bus is-a vehicle, an employee is-a person, circle is-a geometric shape etc. The is-a relationship
has been modeled in terms of inheritance that you have already studied in Lectures 15-18.

The uses-a relationship demonstrate that an object of one specific type uses an object of different type to
perform some activity. For example, a person uses-a wiper to wash bus window pane, a teacher uses-a
course to teach student, a cyclist uses-a pump in tire-pumping activity). The uses-a relationship can be
described as association between objects i.e. a teacher has association with student through a specific

134
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

course. Similarly, university has association with its departments through administration. In simple words,
association is a relationship between objects where exists no ownership and each object has its own
lifecycle. More specifically, association are of two types i.e. aggregation and composition that represents
has-a relationship between objects.

The has-a relationship represents a classical ownership of whole-part relationship. Sometimes an object of
one type contains an object of type e.g. a university has-a number of departments and ultimately a
department has a number of professors, a bus has-an engine, a bike has-a set of wheels etc. The has-a
relationship can be modeled as aggregation and composition.

● Aggregation is type of association representing weak relationship. In aggregation, contained object


exists even after the release of an owning object. Hence, in aggregation, there exists ownership without
life-cycle dependency. For example, if a company no longer exists even then employee of that will
continue to exist.
● Composition is a special type of aggregation representing strong relationship in which the life-cycle of
the part is dependent on the whole. Existence of the part is directly dependent on the existence of the
whole. For example, the relationship between vehicle and its engine. Engine is build and destroyed
whenever a vehicle is build or destroyed, respectively.

104. Homework before Lab

104.1 Problem Solution Modeling


Draw UML class diagrams of the following task. You are required to bring this design with you and
submit to your lab instructor.

5.1.1 Problem description:

A T20 is made up of at least 10 teams. Each cricket team is composed of 10 players, and one player captains
the team. A team has a name and a record. Players have a number and a position. Cricket teams play games
against each other. Each game has a score and a location. Teams are sometimes lead by a coach. A coach
has a level of accreditation and a number of years of experience, and can coach multiple teams. Coaches
and players are people, and people have names and addresses.

Draw UML diagram for each class and show inheritance, association, aggregation and composition
relationship between these classes.

104.2 Practices from home


5.2.1 Task-1

Using C++ compiler, illustrate the implementation of classes that have been specified in section 5.1.1. Write
main() in a way that it clearly describes aggregation and composition relationships between objects of
implemented classes.

135
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

5.2.2 Task-2

Using C++ compiler, demonstrate the implementation of classes in a way that it proves inheritance
relationship between appropriate classes, association and aggregation/composition relationship between
objects of various classes in terms of ownership and lifecycle dependency.

105. Procedure & Tools


105.1 Tools
Visual Studio 2017.

105.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup visual studio and make a project named “RelationshipExample”

105.3 Walkthrough Task [Expected time = 30 mins]


In this task, you are required to write a C++ code which would elaborate the concept of relationships (i.e.
inheritance, aggregation, composition) in OOP. The following lines show the output of a basic relationship
concept:

6.3.1 Writing Code


In the source file, which is created in the project “RelationshipExample” write following C++ code:

136
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: Relationship Example

137
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.

6.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 3: Final Output

106. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab11

106.1 Practice Task 1 [Expected Time =


80 mins]
Consider six classes i.e. Person, Scientist, Engineer, Sector, Laboratory, and Department having
following specifications.

Class Department has


● Two attributes of type string i.e. DepartmentName and location
● An attribute named sect of type Sector

Class Sector has


● Two attributes i.e. sectID, sectName
● A two-argument constructor to initialize data fields with user-defined values
● A member function display() to show all attribute values

Class Laboratory contains


● Three attributes i.e. labID, access_level, sectID and experimentNo
● A three-argument constructor that:
o Initializes labID and experimentNo with user-defined values
o Based on designation, on scale of 1-10 access_level is automatically assigned (higher the
designation higher the access_level)
Class Person has
● Two attributes i.e. name and age
● A parameterized constructor to initialize attributes with user-defined values
● A member function display() to show its attribute values

Class Scientist is derived from class Person and has


● A data field named sciName of type string

138
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● A data field named dept of type Department


● A data field named designation of type string
● A two-argument constructor to initialize both attributes of user-defined values

Class Engineer is derived from class Person and has


● An additional attribute named lab of type Laboratory
● A constructor to initialize lab with user-defined value

a) Draw UML diagram for each class and show inheritance, aggregation, and composition relationship
between these classes.
b) Implement all these classes while illustrating the concept of aggregation and composition in terms
of ownership and life-cycle.

106.2 Practice Task 2 [Expected Time = 40 mins]


Cafeteria system is an important part of any institute. The university wants to automate the
cafeteria system you can help by identifying different classes along with their relationships.
University café has different customers (Employees, Students) that visit it for buying different
kinds of food. We want to make the system online so when a customer wants something he should
order it through a server. Whenever a customer comes to café he/she orders the food from specific
category. When a user wants to order something menu is displayed showing different food corners
(FastFood, ProperMeal, Beverages). After the order is placed generate bill for the user according
to the order he has placed. Identify the classes their relationship and function prototype of each
class.

106.3 Outcomes
After completing this lab, student will be able to implement the concepts of association, aggregation, and
composition in terms of ownership and life cycle of associated objects.

106.4 Testing
● For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly elaborated
the concept of aggregation and composition in terms of ownership and life cycle.

Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation Comments


T1

107. Evaluation Task (Unseen) [Expected Time = 40 mins for all tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

139
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

108. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
Table 4: Evaluation of the Lab

Sr. No. Task No Description Marks


1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks (Unseen) 20
4 Comments 5
5 Good Programming 10
Practices
Total Marks 100

109. Further Reading

109.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

109.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

140
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-12)
Reusability VI
Function and Class Templates

141
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
1432.
Activity Time
Boxing 1443.
Objective of the
Experiment 1444.
Concept
Map 1445.
Homework before
Lab 1455.1
Practices from
Home 1456.
Procedure &
Tools 1456.1
Tools
1456.2
Setting-up Visual Studio 2008
1456.3
Walkthrough Task
1457.
Practice
Tasks 1467.1
Practice Task 1
1477.2
Practice Task 2
1477.3
Practice Task 3
1477.4
Outcomes
1477.5
Testing
1478.
Evaluation Task (Unseen)
1489.
Evaluation
Criteria14810. Further
Reading 14810.1
Books
14810.2
Slides
149

142
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 12: Function and Class Templates


110. Introduction
In general, a template is used to represent a pattern. In programming, occasionally, a group of functions
and/or classes differ from each other simply in terms of parameter types or types of data members,
respectively. In these situations, templates are used to avoid redundant coding and can be practiced in two
ways i.e. with functions and with classes. In C++, templates facilitate the programmer to define a generic
function or class that is able to perform the same task with variables of different data types (including
objects of different classes). The syntax of writing a generic function in C++ is given as under:

template<class T> or template<typename T>


T functionName(T value)
{
return value * value;

You can call this function in different ways i.e. with parameters of types int, long, float, double as:

int var1= 10; long var2 = 125321; double var3 = 10.0;


functionName(var1);
functionName(var2);
functionName(var3);

Similarly, the syntax of writing a generic class is given as under:

template<class T> or template<typename T>


class TemplateExample
{
private:
T var;
public:
TemplateExample(T var)
{
this.var = var;
}
};
In order to create two objects containing data members of different data type, you have to write:

TemplateExample<int> TE1;
TemplateExample<double> TE2;

It is clear from above examples that prior to coding a function template or class template you have to provide
template definition statement starting with the keyword template. This template reserved word in C++

143
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

informs the compiler that programmer is going to define a function or class template. Further, the variable
with reserved word class or typename within angle brackets (< >) is known as the template argument. This
template argument is replaced with specific data type with each function call statement.
Relevant Lecture Readings:
● Lectures: 29, 30, 31
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 682- 703

111. Activity Time Boxing


Table 1: Activity Time Boxing

Task Activity Name Activity time Total Time


No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 25 mins each for task 1 and 2 90 mins
40 mins for task 3
8 Evaluation Task 45 min for all assigned task 45 mins
Total Time 170 mins

112. Objective of the Experiment


After completing this lab the student should be able to:
● declare the template function with type parameters.
● use multiple parameters in function templates.
● understand the benefits of templates.
● create function templates with multiple data types.
● develop generic classes using class templates.
● learn the use of standard template libraries (STL).

113. Concept Map


To deal with overloaded functions and various classes (that differ from each other in terms of the types of
data fields), C++ assists programmer to define generic functions and classes while using the concept of
templates. It is important to mention here that templates do not save the amount of memory to be used by
different functions or class objects. However, template approach (that is a very special kind of code
reusability) saves the time of writing multiple functions and classes with same logical task. In this way,
later on, modification(s) can be performed easily while changing code at one place instead of multiple
places.

The statement of template definition in C++ code by itself is not able to generate any code. Code generation
for a specific template function takes place at the time of function invocation. This is due to the fact that
upon function invocation compiler comes to know about the type to substitute template parameter. This is
known as instantiating the function template.

144
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Concerning class templates in C++, it is important to point out here that C++ provides a powerful and
versatile collection of functions and classes for common data structures i.e. vector, stack, queue etc. This
collection of classes is known as Standard Template Library (STL). Functions and classes in STL provides
well-organized and extensible framework to develop certain applications.

114. Homework before Lab

114.1 Practices from Home


5.1.1 Task-1

A function named exchange that takes two values as its parameters and is responsible to swap these values.
It is required from you to implement exchange function as a template. In the main function, test the working
of exchange function by invoking it with parameters of int, long, double, and char data type.

5.1.2 Task-2

Consider a class named Calculator that contains


● Two data members i.e. num1 and num2
● A parameterized constructor to assign values to both data members
● Four functions i.e. addition(), subtraction(), multiplication(), and division() to perform their
respective functions on data members and return result in double

Make the class Calculator into a template and in this way, a user would be able to instantiate it using
different data types for the data members. In the main function, instantiate two objects of Calculator class
with data members of type integer and float, respectively and invoke all functions of class Calculator.

115. Procedure & Tools


115.1 Tools
Visual Studio 2017.

115.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup visual studio and make a project named “TemplateExample”

115.3 Walkthrough Task [Expected time = 30 mins]


In this task, you are required to write a C++ code which would elaborate templates concept. The following
lines show the output of a basic template example using class templates. The program finds the minimum
number from two numbers using templates concept:

6.3.1 Writing Code

In the source file, which is created in the project “TemplateExample” write following C++ code:

145
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: Find minimum number using Class Template

Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.

6.3.3 Executing the Program

A sample output after running the program is shown below:

Figure 2: Final Output

116. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab12

146
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

116.1 Practice Task 1 [Expected Time = 25 mins]


Write a generic function common() that calculates the double of each element in the array and returns the
value which is most frequent in an array. The function arguments should be the address of the array and
its size. Make this function into a template so it will work with an array of any data type i.e. int, long,
double.

116.2 Practice Task 2 [Expected Time = 25 mins]


Write two generic functions (overloaded) named area(). Create function template for the first area()
function that it is able to receive the radius of a circle as its parameter and returns half of the calculated
area of circle as of same data type. Similarly, create function template for the second area() function that
it is able to receive two parameters as length and width of a rectangle and returns the triple of the calculated
area of rectangle as of same data type.

116.3 Practice Task 3 [Expected Time = 40 mins]


Create a class template for a class named Queue that holds

● A single data member as an array named list of size 10 to store certain elements
● A constructor to initialize queue with value 0 or 0.0 at all its indexes
● Three member functions i.e. sort() to sort the elements of the queue, max() that returns the
maximum value present in the queue, min() that returns the smallest value present in the queue,
and return_queue() that returns all the elements of the queue (in case of there being multiple
maximum and minimum values present in the queue, the member functions should return notify
the user of the number of times that value has been repeated in the queue and then return that value
to the main function).

In the main() function, create three objects with different data types of class queue and test the functionality
of member functions for various values of data members for these objects.

116.4 Outcomes
After completing this lab, student will be able to understand the use and working of function and class
templates in C++.

116.5 Testing
● Test cases for Practice Lab 1

Sample Inputs Sample Outputs


int arr = {1,2,3,4,5} 10
maximum_doubled (arr,5)
double arr = {10.11, 2.99, 1.40, 181.98
90.99}
minimun(arr, 4)

147
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

● Test cases for Practice Lab 2

Sample Inputs Sample Outputs


area(5.0) 39.25
area(20.0,10.0) 600.0

● For Practice Lab 3, lab instructor should check the creation of three instances of List class while
each having an array of different data type. Moreover, check the required functionality of member
functions with these instances.
Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation Comments


T1
T2
T3

117. Evaluation Task (Unseen) [Expected Time = 45 mins for all tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

118. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).

Table 4: Evaluation of the Lab

Sr. No. Task No Description Marks


1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks (Unseen) 20
4 Comments 5
5 Good Programming 10
Practices
Total Marks 100

119. Further Reading

119.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

148
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

119.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

149
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-13)
Static keyword in Object Oriented Programming

150
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction 1522. Activity Time Boxing 1563. Objective of the
Experiment 1574. Concept Map 1575. Homework before Lab 1585.1
Practices from home 1586. Procedure & Tools 1596.1 Tools
1596.2 Setting-up Visual Studio 2008 1596.3 Walkthrough Task
1596.3.1 Writing Code 1597. Practice Tasks 1617.1 Practice Task 1
161 1617.2 Practice Task 2 161 1617.3 Outcomes 1617.4
Testing 1618. Evaluation Task (Unseen) 1619. Evaluation
Criteria 16110. Further Reading16210.1 Books 16210.2 Slides 162

151
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 13: Static keyword in Object Oriented


Programming
120. Introduction
There is an important exception to the rule that each object of a class has its own copy of all the data
members of the class. In certain cases, only one copy of a variable should be shared by all objects of a class.
A static data member is used for such propose.. Such a variable represents "class-wide" information (i.e., a
property of the class shared by all instances, not a property of a specific object of the class). The declaration
of a static member begins with keyword static.

In the above figure, consider Object1, Object2 and Object3 are three of a class. Each object has its own
private data members. The class has a static data member that is share among all the object of that class.
This data member has it own memory allocated that is separate from the memory allocated for each object
of that class.
Static keyword can be used as:

1. Variables in functions
Static variables when used inside function are initialized only once. They hold their value even through
function calls

152
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

2. Class objects

Objects declared static are allocated storage in static storage area. They have a scope till the end of program

153
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Static objects are also initialized using constructors like other normal objects.

3. Data members of a class


Static data members of class are those members which are shared by all the objects. Static data
member has a single piece of storage, and is not available as separate copy with each object, like
other non-static data members. Static member variables (data members) are not initialized using
constructor, because these are not dependent on object initialization. Also, it must be initialized
explicitly, always outside the class. If not initialized, Linker will give error. Once the definition

154
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

for static data member is made, user cannot redefine it. Though, arithmetic operations can be
performed on it.

4. Member functions of a class


These functions work for the class as whole rather than for a particular object of a class. It can be called
using an object and the direct member access . Operator But, its more typical to call a static member
function by itself, using class name and scope resolution :: operator. These functions cannot access ordinary
data members and member functions, but only static data members and static member functions.

155
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

• Static function can only access


static data member of class
– className.static_ method ();

Object_of_class.static_method(
);
• Non static member function
can access static and non static
data member of class
– Object_of_class.Non_static_
method ();
Relevant Lecture Readings:
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.

121. Activity Time Boxing


Table 1: Activity Time Boxing

156
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Task Activity Name Activity time Total Time


No.
6.2 Setting-up Visual 5 mins 5 mins
Studio
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 80 mins for assigned task 80 mins
8 Evaluation Task 55 min for all assigned 55 mins
task
Total Time 170 mins

122. Objective of the Experiment


After completing this lab, the student should be able to:
● model relationship between existing classes
● distinguish between association, aggregation, and composition

123. Concept Map


– [objectName].[public member function]
• e1.getCount();
– [Class name].[public mem.
Static data member – access
A public static data member can be access using any object of the class or class name
– [Object Name].[name of static variable]
• e1.count;
– [Class Name] .[name of static variable]
• Employee .count;
A private static member can be access using a public member function
– [objectName].[public member function]
• e1.getCount();
– [Class name].[public member function]
• Employee.getCount();

A static method is a method that can only access static data member of class. It cannot access
non static data member of that class.

Static vs. non static functions

• Static function can only access static data member of class


– className.static_ method ();
– Object_of_class.static_method();
• Non static member function can access static and non static data member of class
– Object_of_class.Non_static_ method ();

157
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

• Static function can only access


static data member of class
– className.static_ method ();

Object_of_class.static_method(
);
• Non static member function
can access static and non static
data member of class
– Object_of_class.Non_static_
method ();
124. Homework before Lab

124.1 Practices from home


5.1.1 Task-1

158
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Create a SavingsAccount class. Use a static data member annualInterestRate to store the annual
interest rate for each of the savers. Each member of the class contains a private data member savingsBalance
indicating the amount the saver currently has on deposit. Provide member function
calculateMonthlyInterest that calculates the monthly interest by multiplying the balance by
annualInterestRate divided by 12; this interest should be added to savingsBalance. Provide a static
member function modifyInterestRate that sets the static annualInterestRate to a new value.
Write a driver program to test class SavingsAccount. Instantiate two different objects of class
SavingsAccount, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set the
annualInterestRate to 3 percent. Then calculate the monthly interest and print the new balances for each of
the savers. Then set the annualInterestRate to 4 percent, calculate the next month's interest and print the
new balances for each of the savers.

125. Procedure & Tools


125.1 Tools
Visual Studio 2017.

125.2 Setting-up Visual Studio 2017 [Expected time = 5 mins]


Setup visual studio and make a project named “StaticExample”

125.3 Walkthrough Task [Expected time = 30


mins]
In this task, you are required to write a C++ code which would elaborate the concept of static keyword in
OOP. The following lines show the output of a basic static keyword concept:

125.3.1 Writing Code

159
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

In the source file, which is created in the project “StaticExample” write following C++ code:

Figure 1: Static Example

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.

6.3.3 Executing the Program


A sample output after running the program is shown below:

160
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 3: Final Output

126. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab13

126.1 Practice Task 1 [Expected Time = 50 mins]

o Create a Calculator class that has following methods: sum, multiply, divide, modulus , sin , cos , tan
The user should be able to call these methods without creating an object of Calculator class.

126.2 Practice Task 2 [Expected Time = 40 mins]

o Create a class employee with data members as name, emp_id, salary and a static variable count.
Count should count total number of objects created for employee. In main() invoke setters and
getters to take input in attributes of employee.

126.3 Outcomes
After completing this lab, student will be able to implement the concepts static keyword.

126.4 Testing
● For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly elaborated
the concept of aggregation and composition in terms of ownership and life cycle.
Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation Comments


T1

127. Evaluation Task (Unseen) [Expected Time = 55 mins for all tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

128. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
Table 4: Evaluation of the Lab

Sr. No. Task No Description Marks


1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8 Evaluation Tasks (Unseen) 20

161
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

4 Comments 5
5 Good Programming 10
Practices
Total Marks 100

129. Further Reading

129.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

129.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

162
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-14)
Friend Functions and Friend Classes

163
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
1662.
Activity Time
boxing 1663.
Objective of the
Experiment 1664.
Concept
Map 1674.1
Friend
Functions 1674.2
Friend
Classes 1675.
Home Work Before
Lab 1685.1
Practices from
Home 1686.
Procedure &
Tools 1686.1
Tools
1686.2
Setting-up Visual Studio 2017
1686.3
Walkthrough Task
1686.3.1
Writing
Code 1686.3.2
Compilation
1706.3.3
Executing the
Program. 1707.
Practice
Tasks 1707.1
Practice Task 1
1707.2
Practice Task 2
1707.3
Practice Task 3
1717.4
Outcomes
1717.5
Testing
1718.
Evaluation Task (Unseen)

164
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

1729.
Evaluation
Criteria 17210.
Further
Reading 17210.1
Books
17210.2
Slides
172

165
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 14: Friend Functions and Friend Classes


130. Introduction
In object oriented programming one of the basic goals was to enforce encapsulation and data hiding. This
is a feature that ensures that class members are not accessible openly. We want to provide access to class
members through a regulated mechanism in which all accesses are accountable and legal.
Friend functions and friend classes provide a technique through which you can relax the access specifiers
and provide direct access. Although this seems an attractive technique but it is not liked by hardcore
programmers because of its over relaxing attitude. The concept of friend functions is still important because
they need to be used in operator overloading which will be practiced in the next lab. Hence this lab attempts
to build new concepts which will be used in the next lab.

Relevant Lecture Material


● Lecture: 11 - 12
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 468-475

131. Activity Time boxing


Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.

5.1 Evaluation of Design 20 mins 25 mins


6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 25 mins 25 mins
7 Practice tasks 25+25+30 (mins) 80 mins
8 Evaluation Task 35 mins 35 mins
Total Time 170 Minutes

132. Objective of the Experiment


After completing this lab the student should be able to:
● Understand the difference between a regular function and a friend function
● Explain the concept of a friend function.
● Develop a friend function.
● Explain the concept of a friend class.
● Develop a friend class.

166
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

133. Concept Map

133.1 Friend Functions


Before going to the syntax of friend functions it is important that we highlight why they are needed. Friend functions
provide a relaxing mechanism through which we can access the private data members of a class directly without any
question being asked. This does not mean that we have relaxed the access specifiers. A friend function provides access
to the private and public data members of a class from only within its body. Friend functions are needed because
sometimes if we have multiple classes and we want to manipulate the class members through a single function.
Another similar scenario is when we want a regular function (that is not member of a class) to access private members
of a class. The final scenario is the use of friend functions in operator overloading (will be discussed in lab 7).
Always remember that friend functions are not members of a class they are just regular functions with special
privileges. In order to make a friend function you have to specify that a particular function is a friend function. This
can be achieved through the following syntax:

class second; //Forward Declaration


class first
{
private:
int member1;
int membern;
public:
friend void display( first , second ); //Friend function prototype
};

class second
{
In private:
the syntax above it must be understood that access specifiers are not applicable on friend functions i.e. whether you
int inmem1;
write the function public or private it has no effect. Another important thing to always remember is that it is
compulsory toint writemem2;
the keyword friend with the function prototype but writing the friend keyword in the function
public:
definition will result in a syntax error. In the above code the friend function is bridge between two classes using a
singlefriend
function.void display(
Creating first,
this environment second
is purely the ); //Friend
programmers choice. function
It is not prototype
necessary that you have a
}; working like a bridge. You can always have a single friend function inside a single class.
function
When discussing friend functions one must remember that friend functions are never part of a class. They are written
in void
the classdisplay(
to show thatfirst o1,
they have secondwith
a friendship o2) //Note
the class. Friend that
functions friend
are not is not
called using the dotwritten
notation or
by{using the scope resolution. Friend functions are called like a conventional function. Now when using the friend
cout<<o1.member1<<o1.membern;
function we can access both public and private data members directly as if there is no such thing as an access specifier.
Ancout<<o2.mem1<<o2.mem2;
important note regarding friend functions is that these functions should not be used to relax the access specifiers.
}
Secondly the friendship of a function is one sided i.e. the function can access the class members but the class cannot
voiddeceleration
access main( ) that are made inside the function.
{
firstFriend
133.2 obj1;Classes
second obj2;
A display(
friend function has access to those classes
obj1,obj2); with which
//Simple it is friend.
calling. Sometimes
Cannot a situation
use the arises when we
dot operator
} to make two classes friends with each other. This means that a class can access the public and private
want
members of another class directly. To achieve this you must right the friend class statement in the
befriending class.

class first
{
private:
friend class second; //Declaration of friend class 167
int member1;
int membern;
public:
first()
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

void main( )
{

first obj1;
second obj2;

obj2.fun( obj1); //cannot call using obj1!


● Obj1 does not contain a function //called fun
}

134. Home Work Before Lab

Provided below is a descriptive problem. Your task is to read the question carefully then research the claims
and submit the answer to your lab instructor.

134.1 Practices from Home


Many programmers argue that friend functions and friend classes are against the ideology of OOP. Explain
why they think this is the fact. What qualities of OOP are affected by friend functions and friend classes.
Explain in detail and submit your written work to the lab instructor. There is no need to write any code for
this task.
135. Procedure & Tools
135.1 Tools
Visual Studio 2017.

135.2 Setting-up Visual Studio 2017 [Expected time = 5


mins]
Setup Visual Studio and make a project named “series”.

135.3 Walkthrough Task [Expected time = 25 mins]


Find the sum of 𝑎1 + 𝑎2 + 𝑎3 + ⋯ + 𝑎𝑛 arithmetic series. In an arithmetic series the difference between
two consecutive numbers is the same throughout the series. Your class is composed of four data members
i.e. the first entry of the series, last entry of the series, total number of entries for which sum is required and
𝑛
finally the sum up to n terms which has the formula 𝑆𝑛 = 2 (𝑎1 + 𝑎𝑛 ). Use a friend function to compute
the sum of the series.

135.3.1 Writing Code


In the source file created in the project “series” write the following C++ code:

168
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

169
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: The series class and the sum friend class. The display function is a friend function.

135.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.

135.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 2: Final output of series project

136. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab06

136.1 Practice Task 1 [Expected time = 25 mins]


Create a class Circle having private attribute of radius. Create another class Square
having a private attribute of length. Now create a friend function that calculates the parameter
of the square, and a friend class Area that should calculate the area of both the circle and the
square?

136.2 Practice Task 2 [Expected time = 25 mins]


Your task is to create two classes namely data and calculation. The calculation class is a friend of the data
class.

170
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

The data class will be composed of two floating point data members namely a and b. The class will also be
composed of a friend function display that can display all the data members.
The calculation class is responsible for performing operations on the data class and hence it has three
functions as follows:
● A function to compute the Square of sums i.e. (𝑎 + 𝑏)2 = 𝑎2 + 𝑏 2 + 2𝑎𝑏
● A function to compute the Square of difference i.e. (𝑎 − 𝑏)2 = 𝑎2 + 𝑏 2 − 2𝑎𝑏

136.3 Practice Task 3 [Expected time = 30 mins]


Your task is to create a class named equation which will have the data members a and b which are the
coefficients of the equation. The class will have three more data members namely result1, result2 and result3
which will store the computed value of equations. Suppose that variables a and b are integers.

● Setters and Getters.


● Then design a friend function which will determine the reults of all three equations.
● Create another friend function which will display the result.

136.4 Outcomes
After completing this lab, students will be able explain the difference between a member function and a
friend function. The students will be able to create friend functions and friend classes. Further they will be
comfortable with the manipulation of objects using both friend functions and classes.

136.5 Testing

Test Cases for Practice Task-2


Sample Inputs Sample Outputs
a=1 (𝑎 + 𝑏)3 =8
b=1 (𝑎 − 𝑏)3 = 0

Test Cases for Practice Task-3

Sample Inputs Sample Outputs

a =1; proot= 1
b =2; nroot = -3
c =-3

171
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table 2: Confirmation of practice tasks T1, T2 and T3

Practice Confirmatio Comments


Tasks n
T1
T2
T3

137. Evaluation Task (Unseen) [Expected time = 35


mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.

138. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.

Table 3: Evaluation of the Lab

Sr. Task No Description Marks


No.
1 4.1 Problem Modelling 10
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with 15
Testing
4 7.2 Practice task 2 with 20
Testing
5 7.3 Practice task 3 with 25
Testing
6 8 Evaluation Tasks 20
(Unseen)
7 Good Programming 5
Practices
Total Marks 100

139. Further Reading

139.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

139.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

172
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

173
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab Manual for Object-Oriented Programming


(LAB-15)
Introduction to Operator Overloading

174
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Table of Contents
1. Introduction
1772.
Activity Time
boxing 1773.
Objective of the
Experiment 1774.
Concept
Map 1784.1
Introduction to Operator
Overloading 1784.2
Which Operators Can Be
Overloaded 1784.3
Operator Overloading – General
Rules 1784.4
Operator Overloading –
Syntax 1784.5
Stream Insertion and Extraction
Operators 1794.6
The Assignment Operator and the Copy
Constructor 1795.
Home Work Before
Lab 1815.1
Practices from
Home 1816.
Procedure &
Tools 1816.1
Tools
1816.2
Setting-up Visual Studio 2008
1816.3
Walkthrough Task
1816.3.1
Writing
Code 1816.3.2
Compilation
1836.3.3
Executing the
Program 1837.
Practice
Tasks 1847.1
Practice Task 1
1847.2
Practice Task 2

175
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

1847.3
Practice Task 3
1857.4
Outcomes
1857.5
Testing
1858.
Evaluation Task (Unseen)
1869.
Evaluation
Criteria 18610.
Further
Reading 18710.1
Books
18710.2
Slides
187

176
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Lab 15: Introduction to Operator Overloading


140. Introduction
In object Oriented Programming perhaps the most exciting and interesting feature is the adaptation of
operators according to our class. We are all familiar with the use of different operators with primitive data
types. But when it comes to abstract data types we have to define each operator individually. The greatest
advantage of defining each operator is that we can adapt/ modify an operator according to our class and the
objects.
As the name indicates, operator overloading is a basically an operator function whose functionality has
been overloaded. In this lab we will explore the concept of operator adaptation and their overloading. Later
on we will overload some operators for problems related to real world. This lab will explain how friend
functions for overloading stream operators.

Relevant Lecture Material


● Lecture: 13
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 291-308

141. Activity Time boxing


Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
5.1 Evaluation of Design 20 mins 25 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 30 mins 30 mins
7 Practice tasks 25+25+20 (mins) 70 mins
8 Evaluation Task 40 mins 40 mins
Total Time 170 Minutes

142. Objective of the Experiment


After completing this lab the student should be able to:
● Express the need for operator overloading.
● Develop an operator overloading function for both unary and binary operators.
● Demonstrate the use of simple arithmetic operators.
● Demonstrate the use of prefix and postfix operators.
● Use friend functions to overload stream operators.
● Explain the difference between the assignment operator and the copy constructor.
● Use operators with class objects.

177
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

143. Concept Map

143.1 Introduction to Operator Overloading


Operator overloading is an attractive feature offered to programmers using classes and objects. It allows you to create
class objects and then manipulate them using operators just like variables of primitive data types. For example we can
add two integers by using the plus operator, but what happens when we apply the plus operator to a class object.
Without the help of operator overloading we cannot manipulate class objects using mathematical and logical operators.
Some people have the opinion that operator overloading only makes your class complex and less understandable.
Another opinion which people have is that we do not need operator overloading because we can use typical member
functions to achieve a similar solution. Both of these opinions are greatly flawed, first of all operator overloading does
not increase the complexity of your code because it provides increased understandability and clarity to the
programmer. The second and most important fact is that you could always use regular member functions to create a
similar mechanism but C++ provides you with a proper technique for incorporating operators in your code. Operator
overloading has an added benefit that it allows the user to manipulate objects using proper operator symbols. This
feature cannot be achieved using member functions.

143.2 Which Operators Can Be Overloaded


C++ provides an extended range of operators that can be overloaded. These operators include the
conventional unary operators, mathematical operators, logical operators, stream operators, parenthesis
operators and many more.
Because C++ provides such a wide range of operators that can be overloaded, therefore this feature of the
language is widely liked and adopted by programmers.

143.3 Operator Overloading – General Rules


Operator overloading allows the programmer to create an operator function that can be used just like any
other function. This means instead of having a textual name for a function your operator function will have
a name that is an operator symbol like +, -, *, / etc.
Before we begin with operator overloading one must memorize some standard rules. The rules are as
follows
● Only those operators can be overloaded that have been defined by C++. This means you cannot create
your own operators. For example ☺ will not qualify as an operator.
● It is not necessary that you overload the entire set of operators for a class. You only overload those that
will be used in your program.
● In a single expression you can use multiple operators but the order of precedence defined by the
language cannot be changed.
● If an operator is unary by nature then it cannot be converted to binary and vice versa.
● When you overload an operator it is purely your choice what comes in the operator function body. This
means you may be using the + operator but in the function body you can perform the / operation. Of
course this is a logical wrong and such things should be prevented. Hence defining the operator is purely
up to the programmer.

143.4 Operator Overloading – Syntax


As explained previously, operator overloading is basically a function that has an operator symbolic name.
The operator function is created inside the class and it is used basically in the main. The code snippet below
shows the + operator being overloaded. The parameter is actually an object of the class because this operator

178
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

is a binary operator that requires one calling object and one object being passed as an argument. The return
type of this function is dependent on what you wish to return. If you are computing an expression having
more than two objects then you will need to create a temporary object and return the object for further
computing of the expression. Refer to the walkthrough task in this lab.
int operator + (classname obj) //The plus operator
{
. . .
}
Similarly the code snippet below shows the pre increment operator being overloaded.
int operator ++ ( ) //The pre increment operator
{
. . .}
Similarly the code snippet below shows the post increment operator being overloaded. The parameter is in
fact never passed; it is just an indicator to show that this function is a post increment operator. Hence
whenever there is an operator with a unary operator then it indicates that you are referring to a post
increment operator.
int operator ++ (int n) //The post increment operator
{
. . . }

143.5 Stream Insertion and Extraction Operators


C++ allows its programmers to overload the stream insertion (<<) and stream extraction (>>) operators so
that they work with abstract types. Stream insertion and extraction operators already work with
conventional data types but when it comes to abstract data types the compiler is not aware of what to do if
we use a class object with cout or cin.
The stream insertion and extraction cannot be overloaded without the help of friend functions. Friend
function provide input or output support with direct access to public and private members of the class.

class DoB
{
private:
int month, day, year;

public:
DoB( )
{
cout <<“Nullary constructor";
o month = day = year = 0;
}
~DoB ( )
{
cout << ”Destructor called";
} ~DoB ( )
friend ostream
{ & operator << ( ostream & os, DoB &d );
friend istream & operator >> ( istream & is, DoB &d );
}; cout << ”Destructor called";
179
}
ostream
friend & operator <<&( operator
ostream ostream & os,
<<DoB( &dostream
) & os, DoB &d );
{
friendosistream & "."
<< d.day << operator >><< ("."istream
<< d.month << d.year;& is, DoB &d );
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

143.6 The Assignment Operator and the Copy Constructor


A very important operator that can be overloaded is the assignment operator(=). A very confusing question
is the difference between an assignment operator and the copy constructor. The simple logical answer is
that copy constructor provides an initializing mechanism where a new object is created by copying contents
of another object.

180
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

On the other hand the assignment operator is used after an object is created. As the name says the assignment
operator will assign values to an object that has already been created.
Your compiler is aware of this difference and hence you cannot call the copy constructor when the
assignment operator is need. The vice versa of this is also true.

144. Home Work Before Lab


Provided below is a statement for a program which you will code and submit to your lab instructor.

144.1 Practices from Home


Create a class called book. The class will contain data members for name, publisher, author and price. Your
task is to create class objects in the main and provide different values to each object. Then design two
functions as follows:
● add( ) – A function that will find the sum of prices of two book objects.
● compare() – A function that will tell the user which book has more price.
145. Procedure & Tools
145.1 Tools
Visual Studio 2008.

145.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “tolltax”.

145.3 Walkthrough Task [Expected time = 30


mins]
Create a class called “toll”. The class represents the toll tax of a vehicle. According to government policy
the toll tax of a vehicle is the number of wheels of vehicle multiplied by 6. Your class should have data
members as follows: wheels, tax, fine. Suppose the fine of a vehicle is 1 rupee. The + operator should work
with multiple objects in main.

● Overload the stream insertion and extraction to input and output data of the objects
● Use the + operator to find the total tax collected in a day.
● Create the ++ operator to fine a particular car.

145.3.1 Writing Code

181
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

In the source file created in the project “tolltax” write the following C++ code:

182
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 1: The “toll” class demonstrating the use of various overloaded operators

145.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.

145.3.3 Executing the Program


A sample output after running the program is shown below. Also run the code with other possible inputs.

183
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Figure 2: Final output of toll class

146. Practice Tasks


This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\dataserver\assignments$\OOP\Lab07

146.1 Practice Task 1 [Expected time = 25 mins]


Create a class Parameter consisting of only 1 data member ‘Value’.
Overload the following operators:
● +
● *
● -
● Insertion Operator
Using the above mentioned overloaded operators determine the following:
● (𝑎 + 𝑏)3 = 3𝑎𝑏(𝑎 + 𝑏) + 𝑏 3 + 𝑎3
● (𝑎 − 𝑏)3 = 𝑎3 + 𝑏 3 − 3𝑎𝑏( 𝑎 − 𝑏)
● (𝑎 + 𝑏)(𝑎 − 𝑏) = 𝑎2 − 𝑏 2

146.2 Practice Task 2 [Expected time = 25 mins]


● Your task is to create a class called fraction. This class will have two integer data members namely
numerator and denominator. To make the task simple suppose that all fraction have the same
denominator i.e. 5. Follow the requirements given below:
● Create a fraction object called sum that will hold the sum of two fractions by using the + operator.
● Create a fraction object called difference that will hold the difference of two fractions by using the –
operator
● Create a fraction object called multiple that will hold the product of any two fractions by using the *

184
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

operator
● Overload the + operator so that it works with a fraction class object.
● Overload the – operator so that it works with a fraction class object.
● Overload the * operator so that it works with a fraction class object.
In the end create a display function through which you can display your fractions.

146.3 Practice Task 3 [Expected time = 20 mins]


⮚ Create a class Point consisting of two data member x and y.
⮚ Overload the following operators:
● +
● -
● Extraction Operator
⮚ Create two objects of class in main() and show the
▪ average of two points (hint: obj1 and obj2 are two points).
▪ Difference between two points

146.4 Outcomes
After completing this lab, students will be able to customize an operator so that it works with their classes.
Students will be able to redefine familiar mathematical operators and also the stream insertion and
extraction operators.

146.5 Testing
Test Cases for Practice Task-1

Sample Inputs Sample Outputs


a= 1 ● (𝑎 + 𝑏)2 = 4
b= 1 ● (𝑎 − 𝑏)2 = 0
● (𝑎 + 𝑏)(𝑎 − 𝑏) = 0

Test Cases for Practice Task-2

Sample Inputs Sample Outputs


obj1.numerator = 1 4
Sum = obj1 + obj2 =
obj1.denominator = 2 2

obj2.numerator = 3 −2
Difference = obj1- obj2 =
obj2.denominator = 2 2

3
Product = obj1*obj2 =
4

185
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Test Cases for Practice Task-3

Sample Inputs Sample Outputs


displacement = 1 Velocity=1
Time = 1 sec
Kinetic energy= 0.5

Table 2: Confirmation of practice tasks T1, T2 and T3

Practice Confirmation Comments


Tasks
T1
T2
T3

147. Evaluation Task (Unseen) [Expected time = 55


mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.

148. Evaluation Criteria


The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.

Table 3: Evaluation of the Lab

Sr. Task No Description Marks


No.
1 4.1 Problem Modelling 10
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with 20
Testing
4 7.2 Practice task 2 with 25
Testing
5 7.2 Practice task 3 with 15
Testing
6 8 Evaluation Tasks 20
(Unseen)
7 Good Programming 5
Practices

186
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing

Total Marks 100

149. Further Reading

149.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

149.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

187

You might also like