SlideShare a Scribd company logo
1 of 146
Download to read offline
Mohammad Ali Jinnah University
Islamabad
LAB MANUAL
OBJECT ORIENTED PROGRAMMING
First Edition
DEPARTMENT OF COMPUTER SCIENCE
ii
Lab Course Development Team
Supervision and Coordination
Dr. Muhammad Abdul Qadir
Professor
Dean Faculty of Computing
Lab Designers
Dr. Muhammad Azhar Iqbal
Assistant Professor
Department of Computer Science
Mr. Hasan Tahir Butt
Lecturer
Department of Computer Science
Mr. Faisal Shahzad
Junior Lecturer
Department of Computer Science
iii
Table of Contents
Preface iv
Lab 1 – Functions and Pointers Recap 1
Lab 2 – Introduction to Classes and Objects 13
Lab 3 – Access Specifiers, Constructors and Destructors 22
Lab 4 – Constructor Overloading and Copy Constructors 32
Lab 5 – Shallow Copy/ Deep Copy and Working with arrays 41
Lab 6 – Friend Functions and Friend Classes 52
Lab 7 – Introduction to Operator Overloading 61
Lab 8 – Inheritance in Object Oriented Programming 72
Lab 9 – The Protected Access Specifier and Types of Inheritance 80
Lab 10 – Multi-level and Multiple Inheritance 89
Lab 11 – Function Overloading and Function Overriding 98
Lab 12 – Polymorphism in Object Oriented Programming 106
Lab 13 – Relationship in Object Oriented Programming 115
Lab 14 – Function and Class Templates 124
Lab 15 – Exception Handling 131
Annexure A – Course Outline 139
Annexure B – Good Programming Practices 140
iv
Preface
earning is a process that requires class instructions and practice labs. If we omit any of
the above then the learning process is clearly flawed. This book is an attempt to
standardize the lab instructions through the development of a lab curriculum that is based on
the class curriculum. This document is intended to be used by lab instructors, course
instructors and students.
The intent of this curriculum is to define a clear lab structure that can be followed by
the lab instructor and the students. In the absence of such curriculum the labs are often run
without any formal structure. Another problem is that there is no grading criteria defined for
each lab which leads to unethical practices. Perhaps one of the greatest problems faced by lab
instructors is that they are unable to keep the students occupied for the entire duration of the
lab due to which the learning process is greatly hampered.
The labs have been developed in a way that there is synchronization between the class
and the lab. The entire book has been divided into 15 labs having duration of 3 hours each.
Students of the course are expected to carefully read the concept map before coming to the
lab. Students come to the lab with a designs/ program that will be handed over to the lab
instructor for further grading. This code/ design is primarily based on previous learning’s and
experiments. Each lab has a detailed walkthrough task which provides a problem statement
and its programmable solution to the students. The students can raise queries about the code
provided and the lab instructor will guide the students on how the solution has been designed.
Thereafter predefined practice questions have been presented such that each question has a
fix duration and grade. Students are graded upon their accomplishments in these practice
tasks. At the end of the lab the lab instructor will assign an unseen task to the students. This
unseen task contains all the concepts taught in the lab. These unseen tasks have a higher level
of complexity and generally have a greater gain in terms of marks.
What sets these labs apart is the fact that a clear grading criteria has been defined for
each lab. Students are aware of the grading criteria and are expected to meet the requirements
for successful completion of each lab.
L
Department of Computer Science,
MAJU
Page 1
Lab Manual for Object Oriented Programming
(LAB-01)
Functions and Pointers - Recap
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 2
Table of Contents
1. Introduction 3
2. Activity Time boxing 3
3. Objective of the Experiment 3
4. Concept Map 4
4.1 Reusability/ Modularity of Code 4
4.2 Function Prototype and Function Definition 4
4.3 Function Arguments and Parameters 4
4.4 Returning a Value from a Function 5
4.5 Pass by Value and Pass by Reference 6
4.6 Pointers 6
5. Home Work Before Lab 7
5.1 Problem Solution Modelling 7
5.2 Practices from home 8
6. Procedure & Tools 8
6.1 Tools 8
6.2 Setting-up Visual Studio 2008 8
6.3 Walkthrough Task 8
7. Practice Tasks 10
7.1 Practice Task 1 10
7.2 Practice Task 2 10
7.3 Practice Task 3 10
7.4 Practice Task 4 10
7.5 Outcomes 10
7.6 Testing 11
8. Evaluation Task (Unseen) 11
9. Evaluation criteria 11
10. Further Reading 12
10.1 Books 12
10.2 Slides 12
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 3
Lab 01: Functions and Pointers - 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 Material
 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 Minutes
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.
 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.
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 4
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<<”The 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 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);
{
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 5
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;
addtwo(3,4);
}
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 being called.
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 6
cout<<addtwo(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 still 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.
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.
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 7
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 below:
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.
5. Home Work Before Lab
5.1 Problem Solution Modelling
Write the pseudo-code of the following task. You are required to bring this code with you and submit to your
b
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 8
lab instructor.
5.1.1 Problem description
Write pseudo-code for a program that will find the factorial of a number. Your task is to also perform checks on the
number entered by the user because the factorial can only be found of an integer and a positive number. Incorporate
these two conditions in you pseudo-code.
5.2 Practices from home
5.2.1 Task-1
In The field of Physics you are aware of the concept of force and acceleration. Your task is to write a program to
find the force if the mass and the acceleration of a body is given. Write a function to perform the calculation. Your
task is to provide the mass and acceleration as arguments to the function and then display the force without returning
a value.
5.2.2 Task-2
Write a program that creates a function to find the area of a cylinder if the radius and height of the cylinder is
provided. The function should return the value of area. The area of a cylinder is 𝜋 𝑟2
ℎ. Consider the figure below for
further clarification.
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]
Setup Visual Studio and make a project named “FindAverage”.
6.3 Walkthrough Task [Expected time = 25 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.
h
r
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 9
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
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
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 10
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 2: 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:
dataserverassignments$OOPLab01
7.1 Practice Task 1 [Expected time = 15 mins]
Write a program that contains a function to find twenty odd numbers starting from a particular number provided by a
user.
7.2 Practice Task 2 [Expected time = 15 mins]
Write a program to find the power of a number if the base and exponent is provided in the main function. Use pass
by reference mechanism to compute the power. Your function should not return a value.
7.3 Practice Task 3 [Expected time = 20 mins]
Write a program that has an integer array having 20 elements. The program should have a function that can receive
the array and then return the sum of all the elements of the array. Use pointers to demonstrate the iteration through
the array.
7.4 Practice Task 4 [Expected time = 35 mins]
Write a program that finds the factorial of a non negative number provided by the user. Since the user can enter a
floating point number hence your input should accommodate floats and ints. To find the factorial of the entered
number you will need to design three functions as follows:
 Function to determine if a number is a whole number or not
 Function to determine if the number is positive or not
 Function to find the actual factorial
Remember that to find the factorial the number must of positive and a whole number. So if any of these conditions
are not met then you cannot determine the factorial.
7.5 Outcomes
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.
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 11
7.6 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Number: 3 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, …
Test Cases for Practice Task-2
Sample Inputs Sample Outputs
Base: 4
Exponent: 11
Result = 4194304
Check that the function works with pass by reference
Test Cases for Practice Task-3
Sample Inputs Sample Outputs
Array having all entries 1 Sum = 20
Check that pointers have been used to iterate the array
Test Cases for Practice Task-4
Sample Inputs Sample Outputs
Number: -5 Invalid Input
Number: 5.5 Invalid Input
Number: 5 120
Table 2: Confirmation of practice tasks T1, T2, T3, T4
Practice Tasks Confirmation Comments
T1
T2
T3
T4
8. Evaluation Task (Unseen) [Expected time = 40 mins]
The lab instructor will assign you unseen tasks depending upon the progress of the students.
9. 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.
Lab 1 - Functions and Pointers - Recap
Department of Computer Science,
MAJU
Page 12
Table 3: Evaluation of the Lab
Sr.
No.
Task No Description Marks
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
Practices
10
Total Marks 100
10. Further Readings
10.1 Books
 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
dataserverjinnah$
Department of Computer Science,
MAJU
Page 13
Lab Manual for Object Oriented Programming
(LAB-02)
Introduction to Classes and Objects
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 14
Table of Contents
1. Introduction 15
2. Activity Time boxing 15
3. Objective of the Experiment 15
4. Concept Map 16
4.1 Object 16
4.2 Data Members 16
4.3 Member Functions 16
4.4 Constant Member Functions 17
4.5 Class 17
4.6 Encapsulation 17
5. Home Work Before Lab 18
5.1 Problem Solution Modelling 18
5.2 Practices from home 18
6. Procedure & Tools 18
6.1 Tools 18
6.2 Setting-up Visual Studio 2008 18
6.3 Walkthrough Task 18
7. Practice Tasks 20
7.1 Practice Task 1 20
7.2 Practice Task 2 20
7.3 Practice Task 3 20
7.4 Outcomes 20
7.5 Testing 20
8. Evaluation Task (Unseen) 21
9. Evaluation Criteria 21
10. Further Reading 21
10.1 Books 21
10.2 Slides 21
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 15
Lab 02: Introduction to Classes and Objects
1. 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 Material
 Lectures: 3, 4
 Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 195-201
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 30 mins 25 mins
7 Practice tasks 25 + 25 + 30 (mins) 80 mins
8 Evaluation Task 45 min 45 mins
Total Time 170 Minutes
3. 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.
 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.
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 16
4. Concept Map
4.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
behaviour. For example, consider the example of a cat. A cat is has both a state and behaviour. The state of a cat is
its attributes namely colour, breed, gender, age, weight, height, etc. Whereas the behaviour of a cat is its sound,
eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique characteristics and
behaviours.
In programming an object is a collection of variables and functions that together have a unique purpose of
identifying a distinctive entity.
4.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.
4.3 Member Functions
Again referring to the concept of an object and the example of a cat. The cat had a number of behaviours or things
that a cat does. In programming these behaviours 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;
class myclass
{
int datamember;
int memberfun(int); // Function prototype
};
int myclass :: memberfun (int x) // Note the scope resolution operator
{
... // Function body
}
void main( )
{
}
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 17
4.4 Constant Member Functions
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;
}
4.5 Class
A class is a collection 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 are the syntax for creating a class.
4.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 ensures 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 come through the door.
using namespace std;
class myclass
{
int datamember;
void memberfun (int)
{
...
}
}; //Semicolon is necessary
void main( )
{
}
using namespace std;
class myclass;
void main( )
{
}
class myclass
{
int datamember;
void memberfun (int)
{
...
}
}; //Semicolon is necessary
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 18
5. Home Work Before Lab
5.1 Problem Solution 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.
5.1.1 Problem description
List down the data members and member functions of a class that will identify a vehicle. 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.
5.2 Practices from home
5.2.1 Task-1
Identify the data members and member functions for a pizza class. The class should have all the relevant attributes
and qualities required for a pizza object. Try to be imaginative in your design. For example consider various sizes,
toppings, base thickness, etc.
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]
Setup Visual Studio and make a project named “cylinder”.
6.3 Walkthrough Task [Expected time = 25 mins]
Write a program that creates a class called cylinder. The data members of the class are radius and height of the
cylinder is provided. Write two functions that set the respective values and then write a single constant function that
will read the values.
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 19
6.3.1 Writing Code
In the source file created in the project “cylinder” write the following C++ code:
Figure 1: Class for creating a cylinder with its relevant data members
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 2: Final output of cylinder program.
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 20
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:
dataserverassignments$OOPLab02
7.1 Practice Task 1 [Expected time = 25 mins]
Write a C++ program that creates a class called laptop. The data members of the class are brand (string), model
(string), serial (int), colour (string), price (float), processor speed (float), RAM (int), screen size(float).
Create member function that will set the individual values. Since the RAM can be upgraded therefore create a
function that allows you to upgrade the RAM only. In the end, create a function that will display all the data
members.
7.2 Practice Task 2 [Expected time = 25 mins]
Write a class called rectangle. Your task is to store the length and width of the rectangle. Write a member function
called increment that will add 1 to the value of length and width. Also write a function that will compute the area of
the rectangle. Finally write a constant function that will display the length, width and area of the rectangle.
Demonstrate the use of the object in the main function. Make sure that the function names are meaningful and self
descriptive.
7.3 Practice Task 3 [Expected time = 30 mins]
Write a program that creates a class called number. Your class will have two data members namely num (float) and
result (int). To find the factorial of the entered number you will need to design three functions as follows:
 Function to determine if a number is a whole number or not
 Function to determine if the number is positive or not
 Function to find the actual factorial
 Function to display the number and its factorial
Remember that to find the factorial the number must of positive and a whole number. So if any of these conditions
are not met then you cannot determine the factorial.
7.4 Outcomes
After completing this lab, students will be able to design a basic class with data members and member functions.
7.5 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Set the following values
Brand = DELL
Model = 1565D
Serial = 123456
Colour = Silver
Price = 64500.5
Processor = 2.8
RAM = 2
Screen = 15.6
Then Modify the RAM to 3
Brand = DELL
Model = 1565D
Serial = 123456
Colour = Silver
Price = 64500.5
Processor = 2.8
RAM = 3
Screen = 15.6
Test Cases for Practice Task-2
Sample Inputs Sample Outputs
Length: 4
width: 10
Length = 5
Width = 11
Area = 55
Lab 2 - Introduction to Classes and Objects
Department of Computer Science,
MAJU
Page 21
call the increment function Check the use of constant function for display
Test Cases for Practice Task-3
Sample Inputs Sample Outputs
Number: -5 Invalid Input
Number: 5.5 Invalid Input
Number: 5 Number = 5
Factorial = 120
Table 2: Confirmation of practice tasks T1, T2 and T3
Practice Tasks Confirmation Comments
T1
T2
T3
8. Evaluation Task (Unseen) [Expected time = 45 Minutes]
The lab instructor will assign you an unseen task depending upon the progress of the students.
9. 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 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 8 Evaluation Tasks (Unseen) 15
7 Good Programming
Practices
10
Total Marks 80
10. Further Reading
10.1 Books
 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
dataserverjinnah$
Department of Computer Science,
MAJU
Page 22
Lab Manual for Object Oriented Programming
(LAB-03)
Access Specifiers, Constructors and Destructors
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 23
Table of Contents
1. Introduction 24
2. Activity Time boxing 24
3. Objective of the Experiment 24
4. Concept Map 25
4.1 Access Specifiers – Public and Private Access 25
4.2 Constructors 25
4.3 Destructors 26
5. Home Work Before Lab 27
5.1 Practices from home 27
6. Procedure & Tools 27
6.1 Tools 27
6.2 Setting-up Visual Studio 2008 27
6.3 Walkthrough Task 27
7. Practice Tasks 29
7.1 Practice Task 1 29
7.2 Outcomes 30
7.3 Testing 30
8. Evaluation Task (Unseen) 30
9. Evaluation Criteria 31
10. Further Reading 31
10.1 Books 31
10.2 Slides 31
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 24
Lab 03: Access Specifiers, Constructors and
Destructors
1. 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 defence 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 Material
 Lectures: 3, 4, 5, 6
 Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 201-212
2. Activity Time boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 40 mins 40 mins
7 Practice tasks 60 mins 60 mins
8 Evaluation Task 55 mins 45 mins
Total Time 170 Minutes
3. 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 specifier.
 Understand the importance of constructors.
 Understand the importance of destructors.
 Use a basic constructor.
 Use a basic destructor.
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 25
4. Concept Map
4.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.
4.2 Constructors
A constructor is a function that is automatically called when an object is created. This function can exhibit the
regular behaviour 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 functions.
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;
myclass::datamember=10; //Syntax Error: private member
obj.memberfun(10);
}
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 26
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.
4.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;
class myclass
{
private:
int datamember; //Private data member
public:
myclass( ); //Class constructor
{
cout<<”Hello you have called the class constructor”;
}
};
void main( )
{
myclass obj;
}
using namespace std;
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”;
}
};
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 27
5. Home Work Before Lab
5.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.
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]
Setup Visual Studio and make a project named “pizza”.
6.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,
extra toppings. Through the use of a constructor initialize the class object. Determine what is public and private in
the class.
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;
c=cnic;
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( );
}
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 28
6.3.1 Writing Code
In the source file created in the project “pizza” write the following C++ code:
Figure 1: The pizza class demonstrating the use of a constructor
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();
}
};
void main()
{
pizza obj;
obj.display( );
}
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 29
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 2: Final output of pizza 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:
dataserverassignments$OOPLab03
7.1 Practice Task 1 [Expected time = 60 mins]
Write a C++ program that creates a program for a new ice cream vendor called LeCream. The management of
LeCream has decided that they are going to sell their ice cream in 7 different flavours namely chocolate, vanilla,
strawberry, mango, tutti fruit, almond crunch and coffee. Carefully design the program by observing the following
rules.
 LeCream is charging Rs 100 for two scoops and Rs 150 for three scoops. Hence you will need a function to
determine the number of scoops and based on that the price. If a user enters more than three scoops your
program should display invalid input and it should exit.
 LeCream allows its customers to purchase a vanilla wafer with their ice cream. If the customer wants to
purchase the wafer he will have to pay an additional Rs 10. This amount should be added to the total
amount payable by the user.
 If the customer asks for chocolate flavour then he will have to pay an additional amount i.e. Rs 120 for two
scoops and Rs 180 for three scopes. Design a function that will be called if the customer chooses flavoured
ice cream.
 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 flavour, number of scoops and wafer
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 30
 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.
7.2 Outcomes
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.
7.3 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Flavour = chocolate
Wafer required = yes
Number of scoops = 3
Your choice of ice cream is as follows
Flavour = chocolate
Number of scoops = 3
Wafer is required
Total price is 190
Thank you for visiting LeCream!
Flavour = Almond crunch
Wafer required = No
Number of scoops = 2
Your choice of ice cream is as follows
Flavour = Almond Crunch
Number of scoops = 2
Wafer is not required
Total price is 100
Thank you for visiting LeCream!
Flavour = Coffee
Wafer required = yes
Number of scoops = 3
Your choice of ice cream is as follows
Flavour = Coffee
Number of scoops = 3
Wafer is Required
Total price is 160
Thank you for visiting LeCream!
Flavour = Mango
Wafer required = No
Number of scoops = 4
Invalid Input
Thank you for visiting LeCream!
Table 2: Confirmation of practice tasks T1
Practice Tasks Confirmation Comments
T1
8. Evaluation Task (Unseen) [Expected time = 45 Mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.
Lab 3 - Access Specifiers, Constructors and Destructors
Department of Computer Science,
MAJU
Page 31
9. 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
3 7.1 Practice task 1 with Testing 50
4 8 Evaluation Tasks (Unseen) 15
5 Good Programming
Practices
10
Total Marks 90
10. Further Reading
10.1 Books
 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
dataserverjinnah$
Department of Computer Science,
MAJU
Page 32
Lab Manual for Object Oriented Programming
(LAB-04)
Constructor Overloading and Copy Constructors
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 33
Table of Contents
1. Introduction 34
2. Activity Time boxing 34
3. Objective of the Experiment 34
4. Concept Map 34
4.1 Function Overloading 34
4.2 Constructor Overloading – Parameterized and Nullary Constructors 35
4.3 Copy Constructors 35
5. Home Work Before Lab 36
5.1 Practices from home 36
6. Procedure & Tools 36
6.1 Tools 36
6.2 Setting-up Visual Studio 2008 36
6.3 Walkthrough Task 36
7. Practice Tasks 38
7.1 Practice Task 1 38
7.2 Practice Task 2 39
7.3 Outcomes 39
7.4 Testing 39
8. Evaluation Task (Unseen) 39
9. Evaluation Criteria 40
10. Further Reading 40
10.1 Books 40
10.2 Slides 40
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 34
Lab 04: Constructor Overloading and Copy
Constructors
1. 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
2. Activity Time boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
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
3. 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.
4. Concept Map
4.1 Function Overloading
Function overloading is an advanced concept in modern languages where two function 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 function can have the same name but there must be a difference in the number
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);
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 35
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.
4.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.
4.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
class example
{
private:
int one;
int two;
float three;
public:
example( ) //Nullary constructor
{
...
}
example (int on, int tw, float th) //Overloaded Constructor:
parameterized ->1
{
...
}
example (int on, float th, int tw) //Another overloaded Constructor
: Parameterized ->2
{
...
}
};
int main()
{
example obj; //Creation through nullary constru
example obj2(1, 2, 3.3); //Creation through first parameterized constru
example obj3(1, 3.3, 2); //Creation through Second parameterized constru
return 0;
}
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 36
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 ourself to the use of the default copy constructor.
The default copy constructor can be explicitly called as follows:
clss obj2(obj1); // Function calling notation
clss obj2 = obj1; //Assignment statement notation
Both statements create an object of the clss 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.
5. Home Work Before Lab
Provided below is a statement for a program which you will code and submit to your lab instructor.
5.1 Practices from home
Your task is to create a class called examination. The class has data members 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.
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]
Setup Visual Studio and make a project named “student”.
6.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.
 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.
6.3.1 Writing Code
In the source file created in the project “student” write the following C++ code:
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 37
Figure 1: The student class demonstrating the use of a parameterized and nullary constructor. Also note the default
copy constructor being used
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()
{
student s1; //Creation through nullary constructor
student s2("Ali", 30); //Creation through parameterized constructor
s1.showall();
s2.showall();
student s3(s1); //Calling copy constructor for s3
s3.showall();
return 0;
}
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 38
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 2: Final output of student 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:
dataserverassignments$OOPLab04
7.1 Practice Task 1 [Expected time = 40 mins]
VISION is a world leader in manufacturing LCD Televisions. The company has decided that it will allow its
customers to give the dimensions of the TV (in length and width). Once the length and width are ordered the
company will manufacture the TV according to your requirements. In this regard they want you to create a program
that will assist them. Carefully read all the instructions and follow the requirements.
 Create a class called vision
 Create three constructors as follows:
- A nullary constructor that calls the setlength( ) and setwidth( ) function.
- A parameterized constructor that will receive the length and width as integers
- A parameterized constructor that will receive the length and width in float
 By using a special function calculate the area of the TV
 Create a function to calculate the price of the TV by multiplying the area with Rs. 65.
 Create a display( ) function to show the details of the purchased TV.
In the main you will construct three objects that demonstrate the use of the three constructors. After calling the
constructor it will take over and will handover control to the area function, and then the price calculation function.
Remember that the user should not have access to modifying the price.
Determine the access specifiers, data members and member functions. Also note that each constructor can / will
have a distinct functionality in its body. Hence do not try to copy code from one constructor to the other. Focus on
the design clarity and quality of your code.
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 39
7.2 Practice Task 2 [Expected time = 10 mins]
Once you have completed the above task you are also required to use the default copy constructor to show that
values have been copied to the new created object. Use the display( ) function to show the individual objects.
7.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.
7.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Using Nullary constructor
Length = 48
Width = 30
Your LCD purchase details are:
Length = 48
Width=30
Price=93600
Using parameterized constructor (integer)
Length = 48
Width = 30
Your LCD purchase details are:
Length = 48
Width=30
Price=93600
Using parameterized constructor (float)
Length = 40.5
Width = 30.5
Your LCD purchase details are:
Length = 48
Width=30
Price=80291.25
Test Cases for Practice Task-2
Sample Inputs Sample Outputs
Initialize only one of the objects and use it for
copying values into another object by using the
copy constructor
Call the display function using the new object;
The new object will contain the values of the previous object.
Table 2: Confirmation of practice tasks T1, T2
Practice Tasks Confirmation Comments
T1
T2
8. Evaluation Task (Unseen) [Expected time = 55 Mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.
Lab 4 - Constructor Overloading and Copy Constructors
Department of Computer Science,
MAJU
Page 40
9. 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
3 7.1 Practice task 1 with Testing 30
4 7.2 Practice task 2 with Testing 20
5 8 Evaluation Tasks (Unseen) 25
6 Good Programming
Practices
10
Total Marks 100
10. Further Reading
10.1 Books
 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
dataserverjinnah$
Department of Computer Science,
MAJU
Page 41
Lab Manual for Object Oriented Programming
(LAB-05)
Shallow Copy / Deep Copy
Working with Arrays
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 42
Table of Contents
1. Introduction 43
2. Activity Time boxing 43
3. Objective of the Experiment 43
4. Concept Map 43
4.1 Creating a customized copy constructor 43
4.2 Shallow Copy Constructor 44
4.3 Deep Copy Constructor 45
4.4 Working with Arrays 46
5. Home Work Before Lab 47
5.1 Practices from Home 47
6. Procedure & Tools 48
6.1 Tools 48
6.2 Setting-up Visual Studio 2008 48
6.3 Walkthrough Task 48
7. Practice Tasks 49
7.1 Practice Task 1 49
7.2 Practice Task 2 49
7.3 Outcomes 50
7.4 Testing 50
8. Evaluation Task (Unseen) 50
9. Evaluation Criteria 50
10. Further Reading 51
10.1 Books 51
10.2 Slides 51
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 43
Lab 05: Deep Copy / Shallow Copy and Arrays in
Classes
1. 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 relationing arrays and constructors. All
these aspects of arrays will be discussed in detail in this lab.
Relevant Lecture Material
 Lectures: 8, 9, 10
2. Activity Time boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
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
3. 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.
4. Concept Map
4.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.
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 44
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.
4.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.
class example
{
private:
int a;
int b;
public:
example (example & parame) //shallow copy constructor
{
a=parame.a;
b=parame.b;
}
void showall( )
{
cout<<"na="<<a;
cout<<"nb="<<b;
}
example( ) //Simple constructor
{
a=10;
b=20;
}
};
int main()
{
example obj1;
example obj2(obj1);
obj1.showall();
obj2.showall();
return 0;
}
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 45
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.
4.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.
(a)
(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.
Object 1
Memory
Copy of
Object 1
Object 1
Memory
Copy of
Object 1
class example
{
private:
char *str;
int len;
public:
example( ); // one normal constructor
example(char *s); // another normal constructor
example(const example &st) //Deep copy constructor
{
len = st.len;
str = new char [len + 1];
strcpy(str, st.str);
}
// other stuff
};
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 46
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.
4.4 Working with Arrays
As explained earlier, arrays are of very importance in every program. The main reason for their importance 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.
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.
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
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
};
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
}
}
// other stuff
};
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 47
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.
Another option which is very popular among programmers is that the size of the array can be stored as a data
member.
5. Home Work Before Lab
Provided below is a statement for a program which you will code and submit to your lab instructor.
5.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.
class example
{
private:
float *a; //Dynamic array as a data member
public:
example(int size)
{
a=new float[size]; //The size is passed from the main
to the constructor
for(int i=0; i<=9;i++)
{
a[i]=0; // put the value 0 in all locations
}
}
void showall (example arr[ ], int size)
//Size is passed to restrict from crossing array boundary
{
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
cout<<arr[i].a[j];
}
}
}
};
int main()
{
const int size=10;
example obj1[size]=example(size);
//array of objects initialized with parameterized constructor
example obj2;
obj2.showall( obj1, size );
return 0;
}
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 48
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]
Setup Visual Studio and make a project named “english”.
6.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.
6.3.1 Writing Code
In the source file created in the project “english” write the following C++ code:
Figure 1: The english class demonstrate
Figure 1: The “english” class demonstrating the use of a constructor and a copy constructor.
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";
} };
int main( )
{
english obj1;
english obj2=obj1;
cout<<"Object one contains data";
obj1.showall();
cout<<"Copied object contains data";
obj2.showall();
return 0;
}
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 49
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 2: Final output of “english” class
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:
dataserverassignments$OOPLab05
7.1 Practice Task 1 [Expected time = 50 mins]
Lamborghini is an international luxury sports car developer stationed in Italy. The company has a reputation for
producing cars that are extremely expensive, powerful and rare. Lamborghini has developed a brand new model
called the Diablo. The company produces a very limited number of Diablo’s each year. The company is producing
the Diablo in only one colour called the “Hot Red”.
When the company has produced a Diablo, the car has a number of attributes like colour, cubic capacity, number of
seats, year of manufacture, engine number, frame number and owner name. Out of these attributes the attributes that
remain the same for all Diablo’s being produced are colour, cubic capacity and number of seats.
Suppose you are working on a system specially designed for the Lamborghini Diablo. Follow the instructions below
for creating the class and objects:
 Store the owners name as a dynamic array data member.
 Create an object named “obj1” and initialize the object.
 Create a copy constructor that can copy all those attributes that remain the same for all cars.
 Generate another object named “obj2” that is created by copying only those attributes that are the same from
“obj1”.
 Initialize the remaining attributes with values of your own.
7.2 Practice Task 2 [Expected time = 15 mins]
Your task is to create a class that contains an integer pointer data member. Create a single object named “one” in the
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 50
main and assign values to the data member of the object. Then create another object named “two” that is a copy of
the “one”. Create a shallow copy constructor 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 object.
7.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.
7.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Colour = Hot Red
Owner = Ali Raza
Year of manufacture = 2013
Seats = 2
Cubic Capacity = 5700
Engine number = 123456
Frame number = 987654
After selective copying only the permanent attributes contain
values.
Colour = Hot Red
Owner =
Year of manufacture =
Seats = 2
Cubic Capacity = 5700
Engine number =
Frame number =
Test Cases for Practice Task-2
Sample Inputs Sample Outputs
Initialize only object “one” and use it for
copying values into object “two” by using the
copy constructor.
Make a modification in object “two”.
Call the display function of object “one”.
Upon calling the display function of object “one” the modified
values will be displayed
Upon calling the display function of object “two” the same
modified values will be shown.
Table 2: Confirmation of practice tasks T1 and T2
Practice Tasks Confirmation Comments
T1
T2
8. Evaluation Task (Unseen) [Expected time = 45 mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.
9. 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.
Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays
Department of Computer Science,
MAJU
Page 51
Table 3: Evaluation of the Lab
Sr.
No.
Task No Description Marks
1 4.1 Problem Modelling 10
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with Testing 30
4 7.2 Practice task 2 with Testing 20
5 8 Evaluation Tasks (Unseen) 25
6 Good Programming
Practices
10
Total Marks 100
10. Further Reading
10.1 Books
 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
dataserverjinnah$
Department of Computer Science,
MAJU
Page 52
Lab Manual for Object Oriented Programming
(LAB-06)
Friend Functions and Friend Classes
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 53
Table of Contents
1. Introduction 54
2. Activity Time boxing 54
3. Objective of the Experiment 54
4. Concept Map 54
4.1 Friend Functions 54
4.2 Friend Classes 56
5. Home Work Before Lab 56
5.1 Practices from Home 56
6. Procedure & Tools 57
6.1 Tools 57
6.2 Setting-up Visual Studio 2008 57
6.3 Walkthrough Task 57
7. Practice Tasks 58
7.1 Practice Task 1 58
7.2 Practice Task 2 59
7.3 Practice Task 3 59
7.4 Outcomes 59
7.5 Testing 59
8. Evaluation Task (Unseen) 60
9. Evaluation Criteria 60
10. Further Reading 60
10.1 Books 60
10.2 Slides 60
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 54
Lab 06: Friend Functions and Friend Classes
1. 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
2. Activity Time boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
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
3. 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.
4. Concept Map
4.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.
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 55
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:
In the syntax above it must be understood that access specifiers are not applicable on friend functions i.e. whether
you write the function in public or private it has no effect. Another important thing to always remember is that it is
compulsory to write the keyword friend with the function prototype but writing the friend keyword in the function
definition will result in a syntax error. In the above code the friend function is bridge between two classes using a
single function. Creating this environment is purely the programmers choice. It is not necessary that you have a
function working like a bridge. You can always have a single friend function inside a single class.
When discussing friend functions one must remember that friend functions are never part of a class. They are written
in the class to show that they have a friendship with the class. Friend functions are not called using the dot notation
or by using the scope resolution. Friend functions are called like a conventional function. Now when using the friend
function we can access both public and private data members directly as if there is no such thing as an access
specifier.
class second; //Forward Declaration
class first
{
private:
int member1;
int membern;
public:
friend void fun( first , second ); //Friend function prototype
};
class second
{
private:
int mem1;
int mem2;
public:
friend void fun( first, second ); //Friend function prototype
};
void fun( first o1, second o2) //Note that friend is not written
{
cout<<o1.member1<<o1.membern;
cout<<o2.mem1<<o2.mem2;
}
void main( )
{
first obj1;
second obj2;
fun( obj1,obj2); //Simple calling. Cannot use the dot operator
}
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 56
An 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
access deceleration that are made inside the function.
4.2 Friend Classes
A friend function has access to those classes with which it is friend. Sometimes a situation arises when we want to
make two classes friends with each other. This means that a class can access the public and private members of
another class directly. To achieve this you must right the friend class statement in the befriending class.
5. 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.
5.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.
class first
{
private:
friend class second; //Declaration of friend class
int member1;
int membern;
public:
first()
{
member1=10;
member2=20;
}
};
class second
{
private:
int mem1;
int mem2;
public:
void fun( first o1) //Friend function prototype
{
cout<<o1.member1<<o1.membern;
cout<<mem1<<mem2;
}
};
void main( )
{
first obj1;
second obj2;
obj2.fun( obj1); //cannot call using obj1! Obj1 does not contain a
function called fun
}
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 57
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.
6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]
Setup Visual Studio and make a project named “series”.
6.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.
6.3.1 Writing Code
In the source file created in the project “series” write the following C++ code:
class series
{
friend class sum; //Friend class declaration
int first; //First number
int nterm; //Last number
int entries; //Total number of entries
int sumn; //Sum up till n terms
public:
series(int f, int n, int e)
{
first=f;
nterm=n;
entries=e;
}
friend void display(series); //Simple friend function
};
class sum
{
public:
void series_sum(series &obj)
{
obj.sumn=(obj.entries)*(obj.first+obj.nterm)/2;
}
};
void display(series obj) //Friend Function body
{
cout<<"The sum of series is "<<obj.sumn<<endl;
}
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 58
Figure 1: The series class and the sum friend class. The display function is a friend function.
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 2: Final output of series project
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:
dataserverassignments$OOPLab06
7.1 Practice Task 1 [Expected time = 25 mins]
As you know in mathematics the quadratic equation is a very popular 2nd
degree equation. Although there are many
possible methods of solving the quadratic equation, a very popular method is through the use of quadratic formula.
The quadratic equation is 𝑎𝑥2
+ 𝑏𝑥 + 𝑐 = 0 and its roots can be determined using the quadratic formula as follows:
−𝑏 ± 𝑏2 − 4𝑎𝑐
2𝑎
where 𝑎 ≠ 0
int main()
{
series obj1(6,96,31); //(first term, last term, total number of terms)
sum obj2;
obj2.series_sum(obj1);
display(obj1); //Call the friend function
system ("pause");
return 0;
}
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 59
Your task is to create a class named equation which will have the data members a, b and c which are the coefficients
of the quadratic equation. The class will have two more data members namely proot and nroot which stand for the
positive root and negative root of the equation. Suppose that variables a, b and c are integers. Where proot and nroot
are floats.
 Construct the class objects by using a nullary constructor.
 Then design a friend function which will determine the proot and nroot of the equation.
 Create another friend function which will display the values of proot and nroot.
7.2 Practice Task 2 [Expected time = 25 mins]
Your task is to create two classes namely number and computation. The computation class is a friend of the number
class.
The number class will be composed of three floating point data members namely a, b and c. The class will also be
composed of a friend function display that can display all the data members.
The computation class is responsible for performing operations on the number class and hence it has three functions
as follows:
 A function to compute the square of sums i.e. 𝑎 + 𝑏 + 𝑐 2
= 𝑎2
+ 𝑏2
+ 𝑐2
+ 2𝑎𝑏 + 2𝑏𝑐 + 2𝑐𝑎
 A function to compute the square of difference i.e. 𝑎 − 𝑏 − 𝑐 2
= 𝑎2
+ 𝑏2
+ 𝑐2
− 2𝑎𝑏 − 2𝑏𝑐 − 2𝑐𝑎
 A function to compute the mean of the three numbers
7.3 Practice Task 3 [Expected time = 30 mins]
Create a class called matrix that will find the sum of two matrices. To perform this task you will need to create three
private array data members that will hold the original arrays and an array to hold the sum of the matrices.
Suppose that the size of the matrices is 3x3.
Create a friend function which will add the matrices and store the result in the sum matrix. The sum of two matrices
is the sum of corresponding entries.
7.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.
7.5 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
a =1;
b =2;
c =-3
proot= 1
nroot = -3
Test Cases for Practice Task-2
Sample Inputs Sample Outputs
a=1
b=2
c=3
𝑎 + 𝑏 + 𝑐 2
=36
𝑎 − 𝑏 − 𝑐 2
= 16
Mean = 2
Lab 6 - Friend Functions and Friend Classes
Department of Computer Science,
MAJU
Page 60
Test Cases for Practice Task-3
Sample Inputs Sample Outputs
Create the following entries for 3x3 arrays
𝐴 =
1 2 3
4 5 6
7 8 9
𝐵 =
1 2 3
4 5 6
7 8 9
Results should be as follows.
𝐴 + 𝐵 =
2 4 6
8 10 12
14 16 18
Table 2: Confirmation of practice tasks T1, T2 and T3
Practice Tasks Confirmation Comments
T1
T2
T3
8. Evaluation Task (Unseen) [Expected time = 35 mins]
The lab instructor will assign you an unseen task depending upon the progress of the students.
9. 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
3 7.1 Practice task 1 with Testing 15
4 7.2 Practice task 2 with Testing 20
5 7.3 Practice task 3 with Testing 25
6 8 Evaluation Tasks (Unseen) 20
7 Good Programming
Practices
5
Total Marks 100
10. Further Reading
10.1 Books
 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
dataserverjinnah$
Department of Computer Science,
MAJU
Page 61
Lab Manual for Object Oriented Programming
(LAB-07)
Introduction to Operator Overloading
Lab 7 – Introduction to Operator Overloading
Department of Computer Science,
MAJU
Page 62
Table of Contents
1. Introduction 63
2. Activity Time boxing 63
3. Objective of the Experiment 63
4. Concept Map 63
4.1 Introduction to Operator Overloading 63
4.2 Which Operators Can Be Overloaded 64
4.3 Operator Overloading – General Rules 64
4.4 Operator Overloading – Syntax 64
4.5 Stream Insertion and Extraction Operators 65
4.6 The Assignment Operator and the Copy Constructor 66
5. Home Work Before Lab 66
5.1 Practices from Home 66
6. Procedure & Tools 66
6.1 Tools 66
6.2 Setting-up Visual Studio 2008 66
6.3 Walkthrough Task 66
7. Practice Tasks 69
7.1 Practice Task 1 69
7.2 Practice Task 2 69
7.3 Practice Task 3 69
7.4 Outcomes 70
7.5 Testing 70
8. Evaluation Task (Unseen) 71
9. Evaluation Criteria 71
10. Further Reading 71
10.1 Books 71
10.2 Slides 71
Lab 7 – Introduction to Operator Overloading
Department of Computer Science,
MAJU
Page 63
Lab 07: Introduction to Operator Overloading
1. 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
2. Activity Time boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
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
3. 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.
4. Concept Map
4.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.
Lab 7 – Introduction to Operator Overloading
Department of Computer Science,
MAJU
Page 64
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.
4.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.
4.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.
4.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 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
{
. . . }
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual

More Related Content

What's hot

Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
Tech_MX
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
daxesh chauhan
 
Object persistence
Object persistenceObject persistence
Object persistence
Vlad Vega
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 

What's hot (20)

Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Input output streams
Input output streamsInput output streams
Input output streams
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Bootstrapping in Compiler
Bootstrapping in CompilerBootstrapping in Compiler
Bootstrapping in Compiler
 
SPL 1 | Introduction to Structured programming language
SPL 1 | Introduction to Structured programming languageSPL 1 | Introduction to Structured programming language
SPL 1 | Introduction to Structured programming language
 
Object persistence
Object persistenceObject persistence
Object persistence
 
C# String
C# StringC# String
C# String
 
1.python interpreter and interactive mode
1.python interpreter and interactive mode1.python interpreter and interactive mode
1.python interpreter and interactive mode
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Ch 4 linker loader
Ch 4 linker loaderCh 4 linker loader
Ch 4 linker loader
 
Procedural vs. object oriented programming
Procedural vs. object oriented programmingProcedural vs. object oriented programming
Procedural vs. object oriented programming
 
loaders and linkers
 loaders and linkers loaders and linkers
loaders and linkers
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 

Viewers also liked

Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
Prabhu D
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
Laura Popovici
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
Asfand Hassan
 
Travel management
Travel managementTravel management
Travel management
1Parimal2
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
kelleyc3
 

Viewers also liked (20)

Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Lab manual of C++
Lab manual of C++Lab manual of C++
Lab manual of C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Computer science project work
Computer science project workComputer science project work
Computer science project work
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Oop lecture 1_v_2
Oop lecture 1_v_2Oop lecture 1_v_2
Oop lecture 1_v_2
 
Tutorial
TutorialTutorial
Tutorial
 
Travel management
Travel managementTravel management
Travel management
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
Programming II LAB 3 - OOP
Programming II LAB 3 - OOPProgramming II LAB 3 - OOP
Programming II LAB 3 - OOP
 
Programming II LAB 4 (OOP) inheritance
Programming II LAB 4 (OOP)  inheritanceProgramming II LAB 4 (OOP)  inheritance
Programming II LAB 4 (OOP) inheritance
 
Ooad lab manual
Ooad  lab manualOoad  lab manual
Ooad lab manual
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Final year project report on Internet And Interanet Emailing server
Final year project report on Internet And Interanet Emailing serverFinal year project report on Internet And Interanet Emailing server
Final year project report on Internet And Interanet Emailing server
 

Similar to Object Oriented Programming Lab Manual

Sheet1Individual Needs Appointment for Hair StylingEmployee gr.docx
Sheet1Individual Needs Appointment for Hair StylingEmployee gr.docxSheet1Individual Needs Appointment for Hair StylingEmployee gr.docx
Sheet1Individual Needs Appointment for Hair StylingEmployee gr.docx
lesleyryder69361
 
HND Assignment Brief Session Sept.docx
              HND Assignment Brief               Session Sept.docx              HND Assignment Brief               Session Sept.docx
HND Assignment Brief Session Sept.docx
joyjonna282
 
Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7
ashhadiqbal
 
final_year_project_presentation
final_year_project_presentationfinal_year_project_presentation
final_year_project_presentation
Sasui Hidayatullah
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
I202-ST221-Algorithms-and-Data-Structures.pdf
I202-ST221-Algorithms-and-Data-Structures.pdfI202-ST221-Algorithms-and-Data-Structures.pdf
I202-ST221-Algorithms-and-Data-Structures.pdf
SANTOS400018
 
Preliminry report
 Preliminry report Preliminry report
Preliminry report
Jiten Ahuja
 

Similar to Object Oriented Programming Lab Manual (20)

Blue Prism Training Agenda
Blue Prism Training AgendaBlue Prism Training Agenda
Blue Prism Training Agenda
 
Be cse
Be cseBe cse
Be cse
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
Chemlab
ChemlabChemlab
Chemlab
 
Sheet1Individual Needs Appointment for Hair StylingEmployee gr.docx
Sheet1Individual Needs Appointment for Hair StylingEmployee gr.docxSheet1Individual Needs Appointment for Hair StylingEmployee gr.docx
Sheet1Individual Needs Appointment for Hair StylingEmployee gr.docx
 
HND Assignment Brief Session Sept.docx
              HND Assignment Brief               Session Sept.docx              HND Assignment Brief               Session Sept.docx
HND Assignment Brief Session Sept.docx
 
Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7Comp 220 ilab 6 of 7
Comp 220 ilab 6 of 7
 
SE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSSE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUS
 
12th ip CBSE chapter 4 oop in java notes complete
12th ip CBSE  chapter 4 oop in java notes complete12th ip CBSE  chapter 4 oop in java notes complete
12th ip CBSE chapter 4 oop in java notes complete
 
final_year_project_presentation
final_year_project_presentationfinal_year_project_presentation
final_year_project_presentation
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Day 1 (1).pptx
Day 1 (1).pptxDay 1 (1).pptx
Day 1 (1).pptx
 
DITEC - Software Engineering
DITEC - Software EngineeringDITEC - Software Engineering
DITEC - Software Engineering
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 
I202-ST221-Algorithms-and-Data-Structures.pdf
I202-ST221-Algorithms-and-Data-Structures.pdfI202-ST221-Algorithms-and-Data-Structures.pdf
I202-ST221-Algorithms-and-Data-Structures.pdf
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 
3350703
33507033350703
3350703
 
Preliminry report
 Preliminry report Preliminry report
Preliminry report
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

Object Oriented Programming Lab Manual

  • 1. Mohammad Ali Jinnah University Islamabad LAB MANUAL OBJECT ORIENTED PROGRAMMING First Edition DEPARTMENT OF COMPUTER SCIENCE
  • 2. ii Lab Course Development Team Supervision and Coordination Dr. Muhammad Abdul Qadir Professor Dean Faculty of Computing Lab Designers Dr. Muhammad Azhar Iqbal Assistant Professor Department of Computer Science Mr. Hasan Tahir Butt Lecturer Department of Computer Science Mr. Faisal Shahzad Junior Lecturer Department of Computer Science
  • 3. iii Table of Contents Preface iv Lab 1 – Functions and Pointers Recap 1 Lab 2 – Introduction to Classes and Objects 13 Lab 3 – Access Specifiers, Constructors and Destructors 22 Lab 4 – Constructor Overloading and Copy Constructors 32 Lab 5 – Shallow Copy/ Deep Copy and Working with arrays 41 Lab 6 – Friend Functions and Friend Classes 52 Lab 7 – Introduction to Operator Overloading 61 Lab 8 – Inheritance in Object Oriented Programming 72 Lab 9 – The Protected Access Specifier and Types of Inheritance 80 Lab 10 – Multi-level and Multiple Inheritance 89 Lab 11 – Function Overloading and Function Overriding 98 Lab 12 – Polymorphism in Object Oriented Programming 106 Lab 13 – Relationship in Object Oriented Programming 115 Lab 14 – Function and Class Templates 124 Lab 15 – Exception Handling 131 Annexure A – Course Outline 139 Annexure B – Good Programming Practices 140
  • 4. iv Preface earning is a process that requires class instructions and practice labs. If we omit any of the above then the learning process is clearly flawed. This book is an attempt to standardize the lab instructions through the development of a lab curriculum that is based on the class curriculum. This document is intended to be used by lab instructors, course instructors and students. The intent of this curriculum is to define a clear lab structure that can be followed by the lab instructor and the students. In the absence of such curriculum the labs are often run without any formal structure. Another problem is that there is no grading criteria defined for each lab which leads to unethical practices. Perhaps one of the greatest problems faced by lab instructors is that they are unable to keep the students occupied for the entire duration of the lab due to which the learning process is greatly hampered. The labs have been developed in a way that there is synchronization between the class and the lab. The entire book has been divided into 15 labs having duration of 3 hours each. Students of the course are expected to carefully read the concept map before coming to the lab. Students come to the lab with a designs/ program that will be handed over to the lab instructor for further grading. This code/ design is primarily based on previous learning’s and experiments. Each lab has a detailed walkthrough task which provides a problem statement and its programmable solution to the students. The students can raise queries about the code provided and the lab instructor will guide the students on how the solution has been designed. Thereafter predefined practice questions have been presented such that each question has a fix duration and grade. Students are graded upon their accomplishments in these practice tasks. At the end of the lab the lab instructor will assign an unseen task to the students. This unseen task contains all the concepts taught in the lab. These unseen tasks have a higher level of complexity and generally have a greater gain in terms of marks. What sets these labs apart is the fact that a clear grading criteria has been defined for each lab. Students are aware of the grading criteria and are expected to meet the requirements for successful completion of each lab. L
  • 5. Department of Computer Science, MAJU Page 1 Lab Manual for Object Oriented Programming (LAB-01) Functions and Pointers - Recap
  • 6. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 2 Table of Contents 1. Introduction 3 2. Activity Time boxing 3 3. Objective of the Experiment 3 4. Concept Map 4 4.1 Reusability/ Modularity of Code 4 4.2 Function Prototype and Function Definition 4 4.3 Function Arguments and Parameters 4 4.4 Returning a Value from a Function 5 4.5 Pass by Value and Pass by Reference 6 4.6 Pointers 6 5. Home Work Before Lab 7 5.1 Problem Solution Modelling 7 5.2 Practices from home 8 6. Procedure & Tools 8 6.1 Tools 8 6.2 Setting-up Visual Studio 2008 8 6.3 Walkthrough Task 8 7. Practice Tasks 10 7.1 Practice Task 1 10 7.2 Practice Task 2 10 7.3 Practice Task 3 10 7.4 Practice Task 4 10 7.5 Outcomes 10 7.6 Testing 11 8. Evaluation Task (Unseen) 11 9. Evaluation criteria 11 10. Further Reading 12 10.1 Books 12 10.2 Slides 12
  • 7. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 3 Lab 01: Functions and Pointers - 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 Material  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 Minutes 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.  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.
  • 8. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 4 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<<”The 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 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); {
  • 9. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 5 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; addtwo(3,4); } 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 being called.
  • 10. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 6 cout<<addtwo(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 still 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. 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.
  • 11. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 7 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 below: 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. 5. Home Work Before Lab 5.1 Problem Solution Modelling Write the pseudo-code of the following task. You are required to bring this code with you and submit to your b
  • 12. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 8 lab instructor. 5.1.1 Problem description Write pseudo-code for a program that will find the factorial of a number. Your task is to also perform checks on the number entered by the user because the factorial can only be found of an integer and a positive number. Incorporate these two conditions in you pseudo-code. 5.2 Practices from home 5.2.1 Task-1 In The field of Physics you are aware of the concept of force and acceleration. Your task is to write a program to find the force if the mass and the acceleration of a body is given. Write a function to perform the calculation. Your task is to provide the mass and acceleration as arguments to the function and then display the force without returning a value. 5.2.2 Task-2 Write a program that creates a function to find the area of a cylinder if the radius and height of the cylinder is provided. The function should return the value of area. The area of a cylinder is 𝜋 𝑟2 ℎ. Consider the figure below for further clarification. 6. Procedure & Tools 6.1 Tools Visual Studio 2008. 6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] Setup Visual Studio and make a project named “FindAverage”. 6.3 Walkthrough Task [Expected time = 25 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. h r
  • 13. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 9 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 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 After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings that are present in your code.
  • 14. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 10 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 2: 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: dataserverassignments$OOPLab01 7.1 Practice Task 1 [Expected time = 15 mins] Write a program that contains a function to find twenty odd numbers starting from a particular number provided by a user. 7.2 Practice Task 2 [Expected time = 15 mins] Write a program to find the power of a number if the base and exponent is provided in the main function. Use pass by reference mechanism to compute the power. Your function should not return a value. 7.3 Practice Task 3 [Expected time = 20 mins] Write a program that has an integer array having 20 elements. The program should have a function that can receive the array and then return the sum of all the elements of the array. Use pointers to demonstrate the iteration through the array. 7.4 Practice Task 4 [Expected time = 35 mins] Write a program that finds the factorial of a non negative number provided by the user. Since the user can enter a floating point number hence your input should accommodate floats and ints. To find the factorial of the entered number you will need to design three functions as follows:  Function to determine if a number is a whole number or not  Function to determine if the number is positive or not  Function to find the actual factorial Remember that to find the factorial the number must of positive and a whole number. So if any of these conditions are not met then you cannot determine the factorial. 7.5 Outcomes 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.
  • 15. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 11 7.6 Testing Test Cases for Practice Task-1 Sample Inputs Sample Outputs Number: 3 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, … Test Cases for Practice Task-2 Sample Inputs Sample Outputs Base: 4 Exponent: 11 Result = 4194304 Check that the function works with pass by reference Test Cases for Practice Task-3 Sample Inputs Sample Outputs Array having all entries 1 Sum = 20 Check that pointers have been used to iterate the array Test Cases for Practice Task-4 Sample Inputs Sample Outputs Number: -5 Invalid Input Number: 5.5 Invalid Input Number: 5 120 Table 2: Confirmation of practice tasks T1, T2, T3, T4 Practice Tasks Confirmation Comments T1 T2 T3 T4 8. Evaluation Task (Unseen) [Expected time = 40 mins] The lab instructor will assign you unseen tasks depending upon the progress of the students. 9. 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.
  • 16. Lab 1 - Functions and Pointers - Recap Department of Computer Science, MAJU Page 12 Table 3: Evaluation of the Lab Sr. No. Task No Description Marks 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 Practices 10 Total Marks 100 10. Further Readings 10.1 Books  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 dataserverjinnah$
  • 17. Department of Computer Science, MAJU Page 13 Lab Manual for Object Oriented Programming (LAB-02) Introduction to Classes and Objects
  • 18. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 14 Table of Contents 1. Introduction 15 2. Activity Time boxing 15 3. Objective of the Experiment 15 4. Concept Map 16 4.1 Object 16 4.2 Data Members 16 4.3 Member Functions 16 4.4 Constant Member Functions 17 4.5 Class 17 4.6 Encapsulation 17 5. Home Work Before Lab 18 5.1 Problem Solution Modelling 18 5.2 Practices from home 18 6. Procedure & Tools 18 6.1 Tools 18 6.2 Setting-up Visual Studio 2008 18 6.3 Walkthrough Task 18 7. Practice Tasks 20 7.1 Practice Task 1 20 7.2 Practice Task 2 20 7.3 Practice Task 3 20 7.4 Outcomes 20 7.5 Testing 20 8. Evaluation Task (Unseen) 21 9. Evaluation Criteria 21 10. Further Reading 21 10.1 Books 21 10.2 Slides 21
  • 19. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 15 Lab 02: Introduction to Classes and Objects 1. 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 Material  Lectures: 3, 4  Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore o Pages: 195-201 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 30 mins 25 mins 7 Practice tasks 25 + 25 + 30 (mins) 80 mins 8 Evaluation Task 45 min 45 mins Total Time 170 Minutes 3. 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.  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.
  • 20. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 16 4. Concept Map 4.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 behaviour. For example, consider the example of a cat. A cat is has both a state and behaviour. The state of a cat is its attributes namely colour, breed, gender, age, weight, height, etc. Whereas the behaviour of a cat is its sound, eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique characteristics and behaviours. In programming an object is a collection of variables and functions that together have a unique purpose of identifying a distinctive entity. 4.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. 4.3 Member Functions Again referring to the concept of an object and the example of a cat. The cat had a number of behaviours or things that a cat does. In programming these behaviours 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; class myclass { int datamember; int memberfun(int); // Function prototype }; int myclass :: memberfun (int x) // Note the scope resolution operator { ... // Function body } void main( ) { }
  • 21. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 17 4.4 Constant Member Functions 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; } 4.5 Class A class is a collection 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 are the syntax for creating a class. 4.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 ensures 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 come through the door. using namespace std; class myclass { int datamember; void memberfun (int) { ... } }; //Semicolon is necessary void main( ) { } using namespace std; class myclass; void main( ) { } class myclass { int datamember; void memberfun (int) { ... } }; //Semicolon is necessary
  • 22. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 18 5. Home Work Before Lab 5.1 Problem Solution 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. 5.1.1 Problem description List down the data members and member functions of a class that will identify a vehicle. 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. 5.2 Practices from home 5.2.1 Task-1 Identify the data members and member functions for a pizza class. The class should have all the relevant attributes and qualities required for a pizza object. Try to be imaginative in your design. For example consider various sizes, toppings, base thickness, etc. 6. Procedure & Tools 6.1 Tools Visual Studio 2008. 6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] Setup Visual Studio and make a project named “cylinder”. 6.3 Walkthrough Task [Expected time = 25 mins] Write a program that creates a class called cylinder. The data members of the class are radius and height of the cylinder is provided. Write two functions that set the respective values and then write a single constant function that will read the values.
  • 23. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 19 6.3.1 Writing Code In the source file created in the project “cylinder” write the following C++ code: Figure 1: Class for creating a cylinder with its relevant data members 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 2: Final output of cylinder program.
  • 24. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 20 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: dataserverassignments$OOPLab02 7.1 Practice Task 1 [Expected time = 25 mins] Write a C++ program that creates a class called laptop. The data members of the class are brand (string), model (string), serial (int), colour (string), price (float), processor speed (float), RAM (int), screen size(float). Create member function that will set the individual values. Since the RAM can be upgraded therefore create a function that allows you to upgrade the RAM only. In the end, create a function that will display all the data members. 7.2 Practice Task 2 [Expected time = 25 mins] Write a class called rectangle. Your task is to store the length and width of the rectangle. Write a member function called increment that will add 1 to the value of length and width. Also write a function that will compute the area of the rectangle. Finally write a constant function that will display the length, width and area of the rectangle. Demonstrate the use of the object in the main function. Make sure that the function names are meaningful and self descriptive. 7.3 Practice Task 3 [Expected time = 30 mins] Write a program that creates a class called number. Your class will have two data members namely num (float) and result (int). To find the factorial of the entered number you will need to design three functions as follows:  Function to determine if a number is a whole number or not  Function to determine if the number is positive or not  Function to find the actual factorial  Function to display the number and its factorial Remember that to find the factorial the number must of positive and a whole number. So if any of these conditions are not met then you cannot determine the factorial. 7.4 Outcomes After completing this lab, students will be able to design a basic class with data members and member functions. 7.5 Testing Test Cases for Practice Task-1 Sample Inputs Sample Outputs Set the following values Brand = DELL Model = 1565D Serial = 123456 Colour = Silver Price = 64500.5 Processor = 2.8 RAM = 2 Screen = 15.6 Then Modify the RAM to 3 Brand = DELL Model = 1565D Serial = 123456 Colour = Silver Price = 64500.5 Processor = 2.8 RAM = 3 Screen = 15.6 Test Cases for Practice Task-2 Sample Inputs Sample Outputs Length: 4 width: 10 Length = 5 Width = 11 Area = 55
  • 25. Lab 2 - Introduction to Classes and Objects Department of Computer Science, MAJU Page 21 call the increment function Check the use of constant function for display Test Cases for Practice Task-3 Sample Inputs Sample Outputs Number: -5 Invalid Input Number: 5.5 Invalid Input Number: 5 Number = 5 Factorial = 120 Table 2: Confirmation of practice tasks T1, T2 and T3 Practice Tasks Confirmation Comments T1 T2 T3 8. Evaluation Task (Unseen) [Expected time = 45 Minutes] The lab instructor will assign you an unseen task depending upon the progress of the students. 9. 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 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 8 Evaluation Tasks (Unseen) 15 7 Good Programming Practices 10 Total Marks 80 10. Further Reading 10.1 Books  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 dataserverjinnah$
  • 26. Department of Computer Science, MAJU Page 22 Lab Manual for Object Oriented Programming (LAB-03) Access Specifiers, Constructors and Destructors
  • 27. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 23 Table of Contents 1. Introduction 24 2. Activity Time boxing 24 3. Objective of the Experiment 24 4. Concept Map 25 4.1 Access Specifiers – Public and Private Access 25 4.2 Constructors 25 4.3 Destructors 26 5. Home Work Before Lab 27 5.1 Practices from home 27 6. Procedure & Tools 27 6.1 Tools 27 6.2 Setting-up Visual Studio 2008 27 6.3 Walkthrough Task 27 7. Practice Tasks 29 7.1 Practice Task 1 29 7.2 Outcomes 30 7.3 Testing 30 8. Evaluation Task (Unseen) 30 9. Evaluation Criteria 31 10. Further Reading 31 10.1 Books 31 10.2 Slides 31
  • 28. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 24 Lab 03: Access Specifiers, Constructors and Destructors 1. 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 defence 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 Material  Lectures: 3, 4, 5, 6  Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore o Pages: 201-212 2. Activity Time boxing Table 1: Activity Time Boxing Task No. Activity Name Activity time Total Time 5.1 Evaluation of Design 20 mins 20 mins 6.2 Setting-up Visual Studio 5 mins 5 mins 6.3 Walkthrough Tasks 40 mins 40 mins 7 Practice tasks 60 mins 60 mins 8 Evaluation Task 55 mins 45 mins Total Time 170 Minutes 3. 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 specifier.  Understand the importance of constructors.  Understand the importance of destructors.  Use a basic constructor.  Use a basic destructor.
  • 29. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 25 4. Concept Map 4.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. 4.2 Constructors A constructor is a function that is automatically called when an object is created. This function can exhibit the regular behaviour 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 functions. 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; myclass::datamember=10; //Syntax Error: private member obj.memberfun(10); }
  • 30. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 26 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. 4.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; class myclass { private: int datamember; //Private data member public: myclass( ); //Class constructor { cout<<”Hello you have called the class constructor”; } }; void main( ) { myclass obj; } using namespace std; 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”; } };
  • 31. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 27 5. Home Work Before Lab 5.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. 6. Procedure & Tools 6.1 Tools Visual Studio 2008. 6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] Setup Visual Studio and make a project named “pizza”. 6.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, extra toppings. Through the use of a constructor initialize the class object. Determine what is public and private in the class. 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; c=cnic; 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( ); }
  • 32. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 28 6.3.1 Writing Code In the source file created in the project “pizza” write the following C++ code: Figure 1: The pizza class demonstrating the use of a constructor 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(); } }; void main() { pizza obj; obj.display( ); }
  • 33. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 29 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 2: Final output of pizza 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: dataserverassignments$OOPLab03 7.1 Practice Task 1 [Expected time = 60 mins] Write a C++ program that creates a program for a new ice cream vendor called LeCream. The management of LeCream has decided that they are going to sell their ice cream in 7 different flavours namely chocolate, vanilla, strawberry, mango, tutti fruit, almond crunch and coffee. Carefully design the program by observing the following rules.  LeCream is charging Rs 100 for two scoops and Rs 150 for three scoops. Hence you will need a function to determine the number of scoops and based on that the price. If a user enters more than three scoops your program should display invalid input and it should exit.  LeCream allows its customers to purchase a vanilla wafer with their ice cream. If the customer wants to purchase the wafer he will have to pay an additional Rs 10. This amount should be added to the total amount payable by the user.  If the customer asks for chocolate flavour then he will have to pay an additional amount i.e. Rs 120 for two scoops and Rs 180 for three scopes. Design a function that will be called if the customer chooses flavoured ice cream.  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 flavour, number of scoops and wafer
  • 34. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 30  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. 7.2 Outcomes 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. 7.3 Testing Test Cases for Practice Task-1 Sample Inputs Sample Outputs Flavour = chocolate Wafer required = yes Number of scoops = 3 Your choice of ice cream is as follows Flavour = chocolate Number of scoops = 3 Wafer is required Total price is 190 Thank you for visiting LeCream! Flavour = Almond crunch Wafer required = No Number of scoops = 2 Your choice of ice cream is as follows Flavour = Almond Crunch Number of scoops = 2 Wafer is not required Total price is 100 Thank you for visiting LeCream! Flavour = Coffee Wafer required = yes Number of scoops = 3 Your choice of ice cream is as follows Flavour = Coffee Number of scoops = 3 Wafer is Required Total price is 160 Thank you for visiting LeCream! Flavour = Mango Wafer required = No Number of scoops = 4 Invalid Input Thank you for visiting LeCream! Table 2: Confirmation of practice tasks T1 Practice Tasks Confirmation Comments T1 8. Evaluation Task (Unseen) [Expected time = 45 Mins] The lab instructor will assign you an unseen task depending upon the progress of the students.
  • 35. Lab 3 - Access Specifiers, Constructors and Destructors Department of Computer Science, MAJU Page 31 9. 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 3 7.1 Practice task 1 with Testing 50 4 8 Evaluation Tasks (Unseen) 15 5 Good Programming Practices 10 Total Marks 90 10. Further Reading 10.1 Books  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 dataserverjinnah$
  • 36. Department of Computer Science, MAJU Page 32 Lab Manual for Object Oriented Programming (LAB-04) Constructor Overloading and Copy Constructors
  • 37. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 33 Table of Contents 1. Introduction 34 2. Activity Time boxing 34 3. Objective of the Experiment 34 4. Concept Map 34 4.1 Function Overloading 34 4.2 Constructor Overloading – Parameterized and Nullary Constructors 35 4.3 Copy Constructors 35 5. Home Work Before Lab 36 5.1 Practices from home 36 6. Procedure & Tools 36 6.1 Tools 36 6.2 Setting-up Visual Studio 2008 36 6.3 Walkthrough Task 36 7. Practice Tasks 38 7.1 Practice Task 1 38 7.2 Practice Task 2 39 7.3 Outcomes 39 7.4 Testing 39 8. Evaluation Task (Unseen) 39 9. Evaluation Criteria 40 10. Further Reading 40 10.1 Books 40 10.2 Slides 40
  • 38. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 34 Lab 04: Constructor Overloading and Copy Constructors 1. 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 2. Activity Time boxing Table 1: Activity Time Boxing Task No. Activity Name Activity time Total Time 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 3. 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. 4. Concept Map 4.1 Function Overloading Function overloading is an advanced concept in modern languages where two function 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 function can have the same name but there must be a difference in the number 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);
  • 39. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 35 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. 4.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. 4.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 class example { private: int one; int two; float three; public: example( ) //Nullary constructor { ... } example (int on, int tw, float th) //Overloaded Constructor: parameterized ->1 { ... } example (int on, float th, int tw) //Another overloaded Constructor : Parameterized ->2 { ... } }; int main() { example obj; //Creation through nullary constru example obj2(1, 2, 3.3); //Creation through first parameterized constru example obj3(1, 3.3, 2); //Creation through Second parameterized constru return 0; }
  • 40. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 36 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 ourself to the use of the default copy constructor. The default copy constructor can be explicitly called as follows: clss obj2(obj1); // Function calling notation clss obj2 = obj1; //Assignment statement notation Both statements create an object of the clss 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. 5. Home Work Before Lab Provided below is a statement for a program which you will code and submit to your lab instructor. 5.1 Practices from home Your task is to create a class called examination. The class has data members 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. 6. Procedure & Tools 6.1 Tools Visual Studio 2008. 6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] Setup Visual Studio and make a project named “student”. 6.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.  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. 6.3.1 Writing Code In the source file created in the project “student” write the following C++ code:
  • 41. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 37 Figure 1: The student class demonstrating the use of a parameterized and nullary constructor. Also note the default copy constructor being used 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() { student s1; //Creation through nullary constructor student s2("Ali", 30); //Creation through parameterized constructor s1.showall(); s2.showall(); student s3(s1); //Calling copy constructor for s3 s3.showall(); return 0; }
  • 42. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 38 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 2: Final output of student 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: dataserverassignments$OOPLab04 7.1 Practice Task 1 [Expected time = 40 mins] VISION is a world leader in manufacturing LCD Televisions. The company has decided that it will allow its customers to give the dimensions of the TV (in length and width). Once the length and width are ordered the company will manufacture the TV according to your requirements. In this regard they want you to create a program that will assist them. Carefully read all the instructions and follow the requirements.  Create a class called vision  Create three constructors as follows: - A nullary constructor that calls the setlength( ) and setwidth( ) function. - A parameterized constructor that will receive the length and width as integers - A parameterized constructor that will receive the length and width in float  By using a special function calculate the area of the TV  Create a function to calculate the price of the TV by multiplying the area with Rs. 65.  Create a display( ) function to show the details of the purchased TV. In the main you will construct three objects that demonstrate the use of the three constructors. After calling the constructor it will take over and will handover control to the area function, and then the price calculation function. Remember that the user should not have access to modifying the price. Determine the access specifiers, data members and member functions. Also note that each constructor can / will have a distinct functionality in its body. Hence do not try to copy code from one constructor to the other. Focus on the design clarity and quality of your code.
  • 43. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 39 7.2 Practice Task 2 [Expected time = 10 mins] Once you have completed the above task you are also required to use the default copy constructor to show that values have been copied to the new created object. Use the display( ) function to show the individual objects. 7.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. 7.4 Testing Test Cases for Practice Task-1 Sample Inputs Sample Outputs Using Nullary constructor Length = 48 Width = 30 Your LCD purchase details are: Length = 48 Width=30 Price=93600 Using parameterized constructor (integer) Length = 48 Width = 30 Your LCD purchase details are: Length = 48 Width=30 Price=93600 Using parameterized constructor (float) Length = 40.5 Width = 30.5 Your LCD purchase details are: Length = 48 Width=30 Price=80291.25 Test Cases for Practice Task-2 Sample Inputs Sample Outputs Initialize only one of the objects and use it for copying values into another object by using the copy constructor Call the display function using the new object; The new object will contain the values of the previous object. Table 2: Confirmation of practice tasks T1, T2 Practice Tasks Confirmation Comments T1 T2 8. Evaluation Task (Unseen) [Expected time = 55 Mins] The lab instructor will assign you an unseen task depending upon the progress of the students.
  • 44. Lab 4 - Constructor Overloading and Copy Constructors Department of Computer Science, MAJU Page 40 9. 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 3 7.1 Practice task 1 with Testing 30 4 7.2 Practice task 2 with Testing 20 5 8 Evaluation Tasks (Unseen) 25 6 Good Programming Practices 10 Total Marks 100 10. Further Reading 10.1 Books  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 dataserverjinnah$
  • 45. Department of Computer Science, MAJU Page 41 Lab Manual for Object Oriented Programming (LAB-05) Shallow Copy / Deep Copy Working with Arrays
  • 46. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 42 Table of Contents 1. Introduction 43 2. Activity Time boxing 43 3. Objective of the Experiment 43 4. Concept Map 43 4.1 Creating a customized copy constructor 43 4.2 Shallow Copy Constructor 44 4.3 Deep Copy Constructor 45 4.4 Working with Arrays 46 5. Home Work Before Lab 47 5.1 Practices from Home 47 6. Procedure & Tools 48 6.1 Tools 48 6.2 Setting-up Visual Studio 2008 48 6.3 Walkthrough Task 48 7. Practice Tasks 49 7.1 Practice Task 1 49 7.2 Practice Task 2 49 7.3 Outcomes 50 7.4 Testing 50 8. Evaluation Task (Unseen) 50 9. Evaluation Criteria 50 10. Further Reading 51 10.1 Books 51 10.2 Slides 51
  • 47. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 43 Lab 05: Deep Copy / Shallow Copy and Arrays in Classes 1. 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 relationing arrays and constructors. All these aspects of arrays will be discussed in detail in this lab. Relevant Lecture Material  Lectures: 8, 9, 10 2. Activity Time boxing Table 1: Activity Time Boxing Task No. Activity Name Activity time Total Time 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 3. 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. 4. Concept Map 4.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.
  • 48. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 44 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. 4.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. class example { private: int a; int b; public: example (example & parame) //shallow copy constructor { a=parame.a; b=parame.b; } void showall( ) { cout<<"na="<<a; cout<<"nb="<<b; } example( ) //Simple constructor { a=10; b=20; } }; int main() { example obj1; example obj2(obj1); obj1.showall(); obj2.showall(); return 0; }
  • 49. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 45 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. 4.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. (a) (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. Object 1 Memory Copy of Object 1 Object 1 Memory Copy of Object 1 class example { private: char *str; int len; public: example( ); // one normal constructor example(char *s); // another normal constructor example(const example &st) //Deep copy constructor { len = st.len; str = new char [len + 1]; strcpy(str, st.str); } // other stuff };
  • 50. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 46 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. 4.4 Working with Arrays As explained earlier, arrays are of very importance in every program. The main reason for their importance 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. 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. 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 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 }; 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 } } // other stuff };
  • 51. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 47 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. Another option which is very popular among programmers is that the size of the array can be stored as a data member. 5. Home Work Before Lab Provided below is a statement for a program which you will code and submit to your lab instructor. 5.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. class example { private: float *a; //Dynamic array as a data member public: example(int size) { a=new float[size]; //The size is passed from the main to the constructor for(int i=0; i<=9;i++) { a[i]=0; // put the value 0 in all locations } } void showall (example arr[ ], int size) //Size is passed to restrict from crossing array boundary { for(int i=0; i<size; i++) { for(int j=0; j<size; j++) { cout<<arr[i].a[j]; } } } }; int main() { const int size=10; example obj1[size]=example(size); //array of objects initialized with parameterized constructor example obj2; obj2.showall( obj1, size ); return 0; }
  • 52. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 48 6. Procedure & Tools 6.1 Tools Visual Studio 2008. 6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] Setup Visual Studio and make a project named “english”. 6.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. 6.3.1 Writing Code In the source file created in the project “english” write the following C++ code: Figure 1: The english class demonstrate Figure 1: The “english” class demonstrating the use of a constructor and a copy constructor. 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"; } }; int main( ) { english obj1; english obj2=obj1; cout<<"Object one contains data"; obj1.showall(); cout<<"Copied object contains data"; obj2.showall(); return 0; }
  • 53. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 49 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 2: Final output of “english” class 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: dataserverassignments$OOPLab05 7.1 Practice Task 1 [Expected time = 50 mins] Lamborghini is an international luxury sports car developer stationed in Italy. The company has a reputation for producing cars that are extremely expensive, powerful and rare. Lamborghini has developed a brand new model called the Diablo. The company produces a very limited number of Diablo’s each year. The company is producing the Diablo in only one colour called the “Hot Red”. When the company has produced a Diablo, the car has a number of attributes like colour, cubic capacity, number of seats, year of manufacture, engine number, frame number and owner name. Out of these attributes the attributes that remain the same for all Diablo’s being produced are colour, cubic capacity and number of seats. Suppose you are working on a system specially designed for the Lamborghini Diablo. Follow the instructions below for creating the class and objects:  Store the owners name as a dynamic array data member.  Create an object named “obj1” and initialize the object.  Create a copy constructor that can copy all those attributes that remain the same for all cars.  Generate another object named “obj2” that is created by copying only those attributes that are the same from “obj1”.  Initialize the remaining attributes with values of your own. 7.2 Practice Task 2 [Expected time = 15 mins] Your task is to create a class that contains an integer pointer data member. Create a single object named “one” in the
  • 54. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 50 main and assign values to the data member of the object. Then create another object named “two” that is a copy of the “one”. Create a shallow copy constructor 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 object. 7.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. 7.4 Testing Test Cases for Practice Task-1 Sample Inputs Sample Outputs Colour = Hot Red Owner = Ali Raza Year of manufacture = 2013 Seats = 2 Cubic Capacity = 5700 Engine number = 123456 Frame number = 987654 After selective copying only the permanent attributes contain values. Colour = Hot Red Owner = Year of manufacture = Seats = 2 Cubic Capacity = 5700 Engine number = Frame number = Test Cases for Practice Task-2 Sample Inputs Sample Outputs Initialize only object “one” and use it for copying values into object “two” by using the copy constructor. Make a modification in object “two”. Call the display function of object “one”. Upon calling the display function of object “one” the modified values will be displayed Upon calling the display function of object “two” the same modified values will be shown. Table 2: Confirmation of practice tasks T1 and T2 Practice Tasks Confirmation Comments T1 T2 8. Evaluation Task (Unseen) [Expected time = 45 mins] The lab instructor will assign you an unseen task depending upon the progress of the students. 9. 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.
  • 55. Lab 5 - Shallow Copy/ Deep Copy, Working With Arrays Department of Computer Science, MAJU Page 51 Table 3: Evaluation of the Lab Sr. No. Task No Description Marks 1 4.1 Problem Modelling 10 2 6 Procedures and Tools 5 3 7.1 Practice task 1 with Testing 30 4 7.2 Practice task 2 with Testing 20 5 8 Evaluation Tasks (Unseen) 25 6 Good Programming Practices 10 Total Marks 100 10. Further Reading 10.1 Books  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 dataserverjinnah$
  • 56. Department of Computer Science, MAJU Page 52 Lab Manual for Object Oriented Programming (LAB-06) Friend Functions and Friend Classes
  • 57. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 53 Table of Contents 1. Introduction 54 2. Activity Time boxing 54 3. Objective of the Experiment 54 4. Concept Map 54 4.1 Friend Functions 54 4.2 Friend Classes 56 5. Home Work Before Lab 56 5.1 Practices from Home 56 6. Procedure & Tools 57 6.1 Tools 57 6.2 Setting-up Visual Studio 2008 57 6.3 Walkthrough Task 57 7. Practice Tasks 58 7.1 Practice Task 1 58 7.2 Practice Task 2 59 7.3 Practice Task 3 59 7.4 Outcomes 59 7.5 Testing 59 8. Evaluation Task (Unseen) 60 9. Evaluation Criteria 60 10. Further Reading 60 10.1 Books 60 10.2 Slides 60
  • 58. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 54 Lab 06: Friend Functions and Friend Classes 1. 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 2. Activity Time boxing Table 1: Activity Time Boxing Task No. Activity Name Activity time Total Time 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 3. 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. 4. Concept Map 4.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.
  • 59. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 55 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: In the syntax above it must be understood that access specifiers are not applicable on friend functions i.e. whether you write the function in public or private it has no effect. Another important thing to always remember is that it is compulsory to write the keyword friend with the function prototype but writing the friend keyword in the function definition will result in a syntax error. In the above code the friend function is bridge between two classes using a single function. Creating this environment is purely the programmers choice. It is not necessary that you have a function working like a bridge. You can always have a single friend function inside a single class. When discussing friend functions one must remember that friend functions are never part of a class. They are written in the class to show that they have a friendship with the class. Friend functions are not called using the dot notation or by using the scope resolution. Friend functions are called like a conventional function. Now when using the friend function we can access both public and private data members directly as if there is no such thing as an access specifier. class second; //Forward Declaration class first { private: int member1; int membern; public: friend void fun( first , second ); //Friend function prototype }; class second { private: int mem1; int mem2; public: friend void fun( first, second ); //Friend function prototype }; void fun( first o1, second o2) //Note that friend is not written { cout<<o1.member1<<o1.membern; cout<<o2.mem1<<o2.mem2; } void main( ) { first obj1; second obj2; fun( obj1,obj2); //Simple calling. Cannot use the dot operator }
  • 60. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 56 An 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 access deceleration that are made inside the function. 4.2 Friend Classes A friend function has access to those classes with which it is friend. Sometimes a situation arises when we want to make two classes friends with each other. This means that a class can access the public and private members of another class directly. To achieve this you must right the friend class statement in the befriending class. 5. 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. 5.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. class first { private: friend class second; //Declaration of friend class int member1; int membern; public: first() { member1=10; member2=20; } }; class second { private: int mem1; int mem2; public: void fun( first o1) //Friend function prototype { cout<<o1.member1<<o1.membern; cout<<mem1<<mem2; } }; void main( ) { first obj1; second obj2; obj2.fun( obj1); //cannot call using obj1! Obj1 does not contain a function called fun }
  • 61. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 57 6. Procedure & Tools 6.1 Tools Visual Studio 2008. 6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins] Setup Visual Studio and make a project named “series”. 6.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. 6.3.1 Writing Code In the source file created in the project “series” write the following C++ code: class series { friend class sum; //Friend class declaration int first; //First number int nterm; //Last number int entries; //Total number of entries int sumn; //Sum up till n terms public: series(int f, int n, int e) { first=f; nterm=n; entries=e; } friend void display(series); //Simple friend function }; class sum { public: void series_sum(series &obj) { obj.sumn=(obj.entries)*(obj.first+obj.nterm)/2; } }; void display(series obj) //Friend Function body { cout<<"The sum of series is "<<obj.sumn<<endl; }
  • 62. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 58 Figure 1: The series class and the sum friend class. The display function is a friend function. 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 2: Final output of series project 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: dataserverassignments$OOPLab06 7.1 Practice Task 1 [Expected time = 25 mins] As you know in mathematics the quadratic equation is a very popular 2nd degree equation. Although there are many possible methods of solving the quadratic equation, a very popular method is through the use of quadratic formula. The quadratic equation is 𝑎𝑥2 + 𝑏𝑥 + 𝑐 = 0 and its roots can be determined using the quadratic formula as follows: −𝑏 ± 𝑏2 − 4𝑎𝑐 2𝑎 where 𝑎 ≠ 0 int main() { series obj1(6,96,31); //(first term, last term, total number of terms) sum obj2; obj2.series_sum(obj1); display(obj1); //Call the friend function system ("pause"); return 0; }
  • 63. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 59 Your task is to create a class named equation which will have the data members a, b and c which are the coefficients of the quadratic equation. The class will have two more data members namely proot and nroot which stand for the positive root and negative root of the equation. Suppose that variables a, b and c are integers. Where proot and nroot are floats.  Construct the class objects by using a nullary constructor.  Then design a friend function which will determine the proot and nroot of the equation.  Create another friend function which will display the values of proot and nroot. 7.2 Practice Task 2 [Expected time = 25 mins] Your task is to create two classes namely number and computation. The computation class is a friend of the number class. The number class will be composed of three floating point data members namely a, b and c. The class will also be composed of a friend function display that can display all the data members. The computation class is responsible for performing operations on the number class and hence it has three functions as follows:  A function to compute the square of sums i.e. 𝑎 + 𝑏 + 𝑐 2 = 𝑎2 + 𝑏2 + 𝑐2 + 2𝑎𝑏 + 2𝑏𝑐 + 2𝑐𝑎  A function to compute the square of difference i.e. 𝑎 − 𝑏 − 𝑐 2 = 𝑎2 + 𝑏2 + 𝑐2 − 2𝑎𝑏 − 2𝑏𝑐 − 2𝑐𝑎  A function to compute the mean of the three numbers 7.3 Practice Task 3 [Expected time = 30 mins] Create a class called matrix that will find the sum of two matrices. To perform this task you will need to create three private array data members that will hold the original arrays and an array to hold the sum of the matrices. Suppose that the size of the matrices is 3x3. Create a friend function which will add the matrices and store the result in the sum matrix. The sum of two matrices is the sum of corresponding entries. 7.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. 7.5 Testing Test Cases for Practice Task-1 Sample Inputs Sample Outputs a =1; b =2; c =-3 proot= 1 nroot = -3 Test Cases for Practice Task-2 Sample Inputs Sample Outputs a=1 b=2 c=3 𝑎 + 𝑏 + 𝑐 2 =36 𝑎 − 𝑏 − 𝑐 2 = 16 Mean = 2
  • 64. Lab 6 - Friend Functions and Friend Classes Department of Computer Science, MAJU Page 60 Test Cases for Practice Task-3 Sample Inputs Sample Outputs Create the following entries for 3x3 arrays 𝐴 = 1 2 3 4 5 6 7 8 9 𝐵 = 1 2 3 4 5 6 7 8 9 Results should be as follows. 𝐴 + 𝐵 = 2 4 6 8 10 12 14 16 18 Table 2: Confirmation of practice tasks T1, T2 and T3 Practice Tasks Confirmation Comments T1 T2 T3 8. Evaluation Task (Unseen) [Expected time = 35 mins] The lab instructor will assign you an unseen task depending upon the progress of the students. 9. 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 3 7.1 Practice task 1 with Testing 15 4 7.2 Practice task 2 with Testing 20 5 7.3 Practice task 3 with Testing 25 6 8 Evaluation Tasks (Unseen) 20 7 Good Programming Practices 5 Total Marks 100 10. Further Reading 10.1 Books  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 dataserverjinnah$
  • 65. Department of Computer Science, MAJU Page 61 Lab Manual for Object Oriented Programming (LAB-07) Introduction to Operator Overloading
  • 66. Lab 7 – Introduction to Operator Overloading Department of Computer Science, MAJU Page 62 Table of Contents 1. Introduction 63 2. Activity Time boxing 63 3. Objective of the Experiment 63 4. Concept Map 63 4.1 Introduction to Operator Overloading 63 4.2 Which Operators Can Be Overloaded 64 4.3 Operator Overloading – General Rules 64 4.4 Operator Overloading – Syntax 64 4.5 Stream Insertion and Extraction Operators 65 4.6 The Assignment Operator and the Copy Constructor 66 5. Home Work Before Lab 66 5.1 Practices from Home 66 6. Procedure & Tools 66 6.1 Tools 66 6.2 Setting-up Visual Studio 2008 66 6.3 Walkthrough Task 66 7. Practice Tasks 69 7.1 Practice Task 1 69 7.2 Practice Task 2 69 7.3 Practice Task 3 69 7.4 Outcomes 70 7.5 Testing 70 8. Evaluation Task (Unseen) 71 9. Evaluation Criteria 71 10. Further Reading 71 10.1 Books 71 10.2 Slides 71
  • 67. Lab 7 – Introduction to Operator Overloading Department of Computer Science, MAJU Page 63 Lab 07: Introduction to Operator Overloading 1. 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 2. Activity Time boxing Table 1: Activity Time Boxing Task No. Activity Name Activity time Total Time 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 3. 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. 4. Concept Map 4.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.
  • 68. Lab 7 – Introduction to Operator Overloading Department of Computer Science, MAJU Page 64 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. 4.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. 4.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. 4.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 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 { . . . }