Lab Manual - Object Oriented Programming - Fall 23 - 14 Labs
Lab Manual - Object Oriented Programming - Fall 23 - 14 Labs
Lab Manual
Fall 2023
1
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Contribution
The manual was last updated on 7th September, 23 by Dr. Umair Rafique.
2
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Table of Contents
3
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Program Logic Don’t know Poor logic in Logic corrects to Correct logic but with Program Logic
(20) about the program some extent but minor mistakes completely correct
programming with major
logic mistakes
Program No task is Makes several Makes few critical Makes some non- Applies the
Implementation implemented critical errors in errors in syntax and critical errors in syntax procedural
(20) syntax and in in applying and in applying knowledge and
applying procedural procedural procedural knowledge syntax in perfect
knowledge knowledge ways
Program Program Program does not Program produces Program produces Program produces
Correctness totally produce correct answers or correct answers or correct answers or
(10) incorrect correct answers or appropriate results appropriate results for appropriate results
appropriate results for most inputs, but most inputs. for all inputs tested
for most inputs. contains
miscalculations in
some cases
Use of Software Don’t know Uses software tool, Uses software tool, Uses software tool, Uses software tool,
Tool about the tool with limited with some with considerable with a high degree
(10) competence competence competence of competence
4
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
5
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-01
Selections, Loops – Recap
6
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
To solve some problems, we must make decisions based on the test of a true-false condition. If the condition
is true, we need to execute a set of statements; if the condition is false, we need to execute another set of
statements (or no statements). This process is referred to as selection.
Additionally, in most programs, we need to repeat lines of code. Repetition allows the program to iterate a
section of code multiple times. C++ provides three constructs for repeating a set of statements without
physically repeating them in the code: while statements, for statements, and do-while statements.
2. Activity Time-boxing
Table 1: Activity Time Boxing
7
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
8
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
If the value of this expression is true, the program executes statement1 and ignores statement2; otherwise,
the program executes statement2 and ignores statement1. Note that in each run, only one of the two
statements, statement1 or statement2, is executed but never both.
5. Homework
No homework task as this is the first lab.
9
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
6.1 Tools
Visual Studio 2017.
Compile and execute the program. A sample output after running the program is shown below. Also run
the code with other possible inputs.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab01.
10
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
7.4 Testing
Test Cases for Practice Task-1
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
11
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
10.1 Book
Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
12
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-02
Functions, Pointers, and Structure – Recap
13
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
C++ programming that you studied in the previous semester is purely based on writing a set of instructions
in a particular sequence such that the output is based on the sequence of the written statements. If this
sequence of instructions is modified then it could have a large impact on the resulting program. Often a
situation arises where we intend to use a particular chunk of code again and again in a single program. In
this scenario using sequential programming the programmer is forced to copy-paste the code in various
locations of the source file.
Although this is a solution, it is not a practical one because it causes the code to become lengthy,
unmanaged, poorly structured and difficult to understand. In such a situation function handling offers an
attractive and easy to implement alternative that is widely accepted and promoted by programmers of all
languages.
This lab is a refresher course on the use of functions, pointers and building logic. The functions that are
designed will receive variables and arrays from the user. The function will perform some processing on the
provided data and return results back to the main program.
The importance of this lab can be highlighted through the fact that functions play a pivotal role in the
establishment of classes, objects and their manipulations. A large portion of object oriented programming
is based on manipulating variables using functions. In the later part of this lab the use of pointers has been
emphasized. Concepts relating to pointers, memory access, using arrays with pointers have been presented.
Relevant Lecture Readings
● Lectures: 1, 2
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Chapters: 5, 10
2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 15 mins 15 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Task 25 mins 25 mins
7 Practice tasks 15 + 15 + 20 + 35 (mins) 85 mins
8 Evaluation Task 40 min for two task 50 mins
Total Time 170 Mins
14
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
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.
15
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Now suppose we are calling the same function from within the main().
void main (){
int x=3, y=4;
addtwo(x, y);
}
For example the following function does not return a value hence the void keyword is used
The value being returned can be displayed by using the following statement from where the function is
being called
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.
16
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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
17
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
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
18
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
In the code above first a simple integer variable is created. Then an integer pointer is created because we
intend to point to an integer variable. The pointer is then given the address of variable x by using the address
operator. Then we use the dereference operator (*) that directs us to the memory location where the pointer
is pointing to.
4.7 Structures
Structure is the collection of variables of different types under a single name for better visualization of
problem. Arrays is also collection of data but arrays can hold data of only one type whereas structure can
hold data of one or more types.
Here a structure person is defined which has three members: name, age and salary.
19
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Output:
20
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Write pseudo-code for a program that will read number n and print the first n numbers in Fibonacci
sequence. Your task is to also perform checks on the number entered by the user as it should be positive
integer. This condition should also be incorporated in your pseudo-code.
5.2.1 Task 1
Every moving object possesses a kinetic energy due to its motion. Your task is to write a program to find
the kinetic energy of an object in motion if the mass and the velocity of that object is given. Write a function
to perform the calculation. Your task is to provide the mass and velocity as arguments to the function and
then display the kinetic energy without returning a value.
5.2.2 Task 2
Write a program that creates a function to find the area of a trapezium if the sides a, b and the height h of
the trapezium are provided. The function should return the value of area. The area of a trapezium is ½(a+b)h.
Consider the figure below for further clarification.
6.1 Tools
Visual Studio 2017.
21
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Figure 3: Function for finding average of values in an arrayIn the code above note that the two functions
use different mechanisms for passing/ using an array. You can choose the method that suits your code/
situation. The size is passed in both functions because without the size the functions can easily cross the
array bounds. Hence passing the array size is a good practice.
6.3.2 Compilation
Write a program to find the power of a number if the base and exponent is provided in the main function.
Use pass by value mechanism to compute the power and return the results back to the main function then
display the result in main function.
22
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab01.
After that, create an array of 5 courses in main function. Create a menu in main function to enable user to
select and perform the operations we created above. Program must not exit until and unless user wants to
do so.
23
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Sample Menu:
Main Menu
---------------
7.5 Testing
Test Cases for Practice Task-1
The lab instructor will give you unseen task depending upon the progress of the class.
24
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
10.1 Books
Text Book:
Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
25
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-03
Introduction to Classes and Objects
26
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 Readings:
a) Revise Lecture: No. 3 and 4
b) Text Book: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 195-201
27
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 behavior. For example, consider the example of a cat. A cat is has both a state and behavior. The state
of a cat is its attributes namely color, breed, gender, age, weight, height, etc. Whereas the behavior of a cat
is its sound, eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique
characteristics and behaviors.
In programming an object is a collection of variables and functions that together have a unique purpose of
identifying a distinctive entity.
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.
class myclass
{
int datamember;
28
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
void main( )
{
4.5 Class
A class is a co0llection of data members and member functions. A class is used to define an abstract data
type. This abstract data type is used in the construction of an object which is used to access all the data
members and member functions. A class has to be created before it can be used. Provided below is the
syntax for creating a class:
29
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 ensure that the data is not openly accessible to the outer
world. The access is provided by the functions that are part of the unit/bundle. This means that the functions
work like doors in a room. You can prevent thieves from breaking in. Only those people can enter who
come through the door.
30
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
5.2.1 Task-1
Identify the data members and member functions for a submarine sandwich class. The class should have all
the relevant attributes and qualities required for a sandwich object. Try to be imaginative in your design.
For example consider various sauces, Mortadella, salads, cheese and other fillings etc.
6.1 Tools
Visual Studio 2008.
31
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Figure 1: Class for creating an arc 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.
32
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab02
Write a class called quadrilateral. Your task is to store the length of all the sides of the quadrilateral and the
value of the 2 opposite angles within the quadrilateral. Then implement member functions:
Demonstrate the use of the object in the main function. Make sure that the function names are meaningful
and self-descriptive.
7.4 Testing
Now you need to perform the following test cases for all practice tasks mentioned above. The test cases
have been made available in Table 2.
33
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
34
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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: \\fs\lectures$
35
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-04
Access Specifiers, Constructors and Destructors
36
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 defense in secure programming. This lab is designed to teach three very basic yet essential concepts of
OOP namely access specifiers, constructor and destructors. Access specifiers provide a technique through
which we can restrict access to data members and member functions. After enforcing access it is important
to reduce our reliance on too many member functions. Constructors offer a very attractive and easy to
implement technique through which we can take steps call procedures whenever an object is created. The
use of constructors is preferred over the use of member functions because constructors are called
automatically and hence they can invoke further functions whereas simple member functions have to be
called sequentially and explicitly one by one every time an object is created. Similarly this lab also focuses
on the use of destructors that are called whenever an object goes out of scope. In this the lab the students
will be familiarized with the use of access specifiers, constructors and destructors.
Relevant Lecture Readings:
● Lectures: 3, 4, 5, 6
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 201-212
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 80 mins 80 mins
8 Evaluation Task 45 mins 45 mins
Total Time 170 Minutes
4. Concept Map
37
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
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);
}
4.2 Constructors
A constructor is a function that is automatically called when an object is created. This function can exhibit
the regular behavior of any function except that it cannot return a value. The reason why constructors are
needed is that unlike regular functions which need to deliberately called, a constructor will be automatically
called when an object is created. Every constructor has a body from where we can call regular member
function a very important question which is often asked is that how does the compiler know that the
constructor function needs to be called automatically? The answer is very simple. A constructor is a function
that has the same name as the class. Whenever an object is created the compiler searches for a function
having the same name as the class i.e. the constructor. Given below is a sample code that shows the class
38
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
void main( )
{ myclass obj; }
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
39
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
class student{
int age;
int cnic;
int semester;
char name;
public:
int setall(int a, int c, int s, int sem, char n) const
{
age = a;
cnic = c;
semester = s;
name = n;
}
}
int myclass :: displayall ( ){
cout<<”The entered data is”<<student.data;
}
void main( ){Student obj; obj::setall( ); obj.displayall( ); obj.setage(); Student
anotherobj;Student::anotherobj::setall();
}
6.1 Tools
Visual Studio 2017.
40
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
41
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab03
42
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
the options good, neutral and bad against the quality of the service provided.
● In the end create a class destructor that displays a thank you message to the user. Design your
program using sound OOP practices. Carefully determine the data members, member functions,
access specifiers, activities to be performed in the constructor. Make sure that you use good naming
conventions in your code. A good design can earn you higher marks.
7.2 Outcome:
After completing this lab, students will be able to design a class that correctly implements class members
by observing access specifiers. The students will also be familiar with the use of a constructor and
destructor.
7.3 Testing
Test Cases for Practice Task-1
43
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.
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 \\fs\lectures$
44
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-05
Constructor Overloading and Copy Constructors
45
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
11.
4. Concept Map
46
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
47
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Both statements create an object of the class. Of course any of the above statements can be used for copying
an object into another object.
Caution: The copy constructor is always called at the time of creating a new object. If at any time after the
creation of objects you copy contents of one object to the other, then the copy constructor is not called. We
will discuss more on this in future lectures.
6.1 Tools
Visual Studio 2017.
48
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Use the default copy constructor to show that copying of simple objects can be accomplished through the
use of the default copy constructor.
class student
{
private:
string name;
int age;
public:
49
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
6.3.2 Compilation
11.1.1 After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab04
50
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
In the above given picture of a passport there is a machine readable code at the bottom of the passport. This code
is a set of 44 characters per row. Following are the contents embedded into this code:
● The only characters used are A–Z, 0–9 and the filler character <.
● The format of the first row is:
● In the name field, spaces, hyphens and other punctuation are represented by <, except apostrophes, which
are skipped. If the names are too long, names are abbreviated to their most significant parts. In that case,
the last position must contain an alphabetic character to indicate possible truncation, and if there is a given
name, the two fillers and at least one character of it must be included.
● The format of the second row is:
51
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
● The check digit calculation is as follows: each position is assigned a value; for the digits 0 to 9 this is the
value of the digits, for the letters A to Z this is 10 to 35, for the filler < this is 0. The value of each position
is then multiplied by its weight; the weight of the first position is 7, of the second it is 3, and of the third it
is 1, and after that the weights repeat 7, 3, 1, and so on. All values are added together and the remainder of
the final value divided by 10 is the check digit.
Write a program that uses accepts a given Machine Readable Code and using a class stores the following 11 parts of
a passport separately after extraction as private data members:
1. Full Name
2. Passport Number
3. Nationality
4. Gender
5. Date of Birth
6. Country of Issuance (Passport Issuance)
7. Date of Issuance (Passport Issuance)
8. Date of Expiry
9. Citizenship Number
10. Passport Type
Create setters and getters for all the member variables and a public method named display to display the all the data
members.
Create three constructors as follows:
1. A nullary constructor that initializes the Citizenship Number as “*****-*******-*”.
2. A parameterized constructor that accepts First Name and Second Name and concatenates them into the data
member “Full Name” in its body.
3. A parameterized constructor that will set Gender, Nationality, and Passport Number as sent in parameters.
52
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 Your Data is:
Full Name = ALMEERA RAZA
Gender = F
Nationality= PAK
Issuance Date= 12-12-12
Expiry Date=12-12-25
Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=RAZA
Using parameterized constructor (string, string) Your Data is:
FirstName=” ALMEERA” Full Name = ALMEERA ZAHID
LastName=”ZAHID” Gender = F
Nationality= PAK
Issuance Date= 12-12-12
Expiry Date=12-12-25
Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=ZAHID
Using parameterized constructor (char, string, string) Your Data is:
Gender = ‘F’ Full Name = ALMEERA ZAHID
Nationality = “PAK” Gender = F
Passport_Numer= Nationality= PAK
”<PAKZAHID<<ALMEERA<<<<<<<<<<<<<<<<<<<<<<<< Issuance Date= 12-12-12
< Expiry Date=12-12-25
HJ00000014PAK9912246F12080547880745349760<78” Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=ZAHID
53
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
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
\\fs\lectures$\
54
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-06
Shallow Copy / Deep Copy and Working with Arrays
55
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 relating arrays and
constructors. All these aspects of arrays will be discussed in detail in this lab.
Relevant Lecture Material
● Lectures: 8, 9, 10
4. Concept Map
56
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
57
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
(a)
Memory
Copy of
Object Object
1 1
(b)
Figure 1: The effect of copy constructors on a pointer data member (a) using shallow copy (b) Using deep
copy
In the code snippet below a deep copy constructor has been provided that creates a copy of a char array.
The data member len is being used to hold the length of the array.
58
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
class example
{
private:
float a[10]; //array as a data member
public:
example() // normal constructor
{
for(int i=0; i<=9;i++)
{
a[i]=0; // put the value 0 in
all locations
}
}
// other stuff
Given
}; below is a class named example that contains a dynamic floating point array “a”. This array can be
initialized with a constructor or with a simple member function as follows. Since this code works with a
dynamic array therefore the size of the array can be provided at run time. In this particular code since the
size is not passed there may be a possibility that the programmer crosses the array boundary.
class example
{
private:
float *a; //Dynamic array as a data member
public:
example() // normal constructor
{
a=new float[10]; //size can be passed from main to
constru
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.
Another option which is very popular among programmers is that the size of the array can be stored as a
data member.
60
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
6.1 Tools
Visual Studio 2017.
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";
} }; 61
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
int main( )
{
english obj1;
english obj2=obj1;
cout<<"Object one contains data";
obj1.showall();
cout<<"Copied object contains data";
obj2.showall();
return 0;
}
Figure 1: The “english” class demonstrating the use of a constructor and a copy constructor.
6.3.2 Compilation
11.1.2 After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
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:
62
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
\\dataserver\assignments$\OOP\Lab05
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
Title = Interstellar After selective copying only the permanent attributes
Air_Date = October 26th,2014 contain values.
Genre = Drama, Mystery Title = Gravity
Type = Movie Air_Date = December 30th,2013
Runtime = 2h 49m Genre = Drama, Mystery
Country = USA Type = Movie
63
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 2: Evaluation of the Lab
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
\\fs\lectures$\
64
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-07
File Handling
65
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
This lab will introduce you about how to implement file handling code in C++. The section 2
presents a table that outlines some major activities and tasks you will do as the part of this lab.
Table 1 also provides the estimated-time for each activity, which will help you to organize your
tasks well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept
Map”) discusses and provides a comprehensive introduction of the topic. Section 5 lists the set of
home-tasks you are required to complete before this lab. Section 6 presents a “walkthrough task”
that you will do as the first practical activity during your lab. The walkthrough task has many small
steps which you should follow as directed in-order to complete the task and to get the desired
output. After that, you will be ready to work on some tasks on your own. The section 7 lists practice
tasks for this purpose. As the part of section 8, your lab instructor will give you some tasks at
runtime and will evaluate those according to the criteria mentioned in section 9. Section 10 lists
some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.
2. Activity Time-boxing
66
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
A file is a collection of information, stored on a computer’s disk. Information can be saved to
files, and then later read and reused. C++ provides the following classes to perform input/output
operations on the files:
● ofstream: Stream class to write in files
● ifstream: Stream class to read from files
● fstream: Stream class to both read and write from/to files.
These classes (ofstream, ifstream, and fstream) are derived from the classes istream, and
ostream. We have already used objects of these stream classes for example: cin (for standard
input), and cout (for standard output). Similarly, we can use the file streams objects to perform
input (read operation) and output (write operation) in the files. File operations are used extensively
in most of the large projects where we have to save the data permanently on the disks.
You can create an ofstream object to perform writing or output operations on the files while the
ifstream object can only be used for reading from the files. If you want to perform both the writing
and reading operations on the file, please use the fstream objects. Before reading/writing to a file,
it must be opened. To open a file, you can call open function of ofstream, ifstream, or fstream.
void open(const char *filename, ios::openmode mode);
In the above function the first argument specifies the name of the file to open. If the file to open is
not in the current directory (where .cpp files reside) provide complete path with filename. The
second parameter specifies the file opening mode. A list of file opening modes is provided in
Appendix (A).
67
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
6.1 Tools
Visual Studio 2017.
68
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
“student.txt”.
6.3.3 Compilation
11.1.3 After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)
11.1.4 Execute the above program. After successful execution of the program a text file named “student.txt” will be
created in the current directory (where your .cpp file resides). You may open the “student.txt” file and examine the
data written in the file.
69
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Read the student information which was written in the previous program example. After reading
the data from “student.txt”, output it to the screen. For reading the file, write following C++ code
(as shown in the Figure 3). This code opens the “student.txt” file for reading student information
and outputs on the screen.
11.1.6
11.1.7
11.1.8
11.1.9
11.1.10
11.1.11
11.1.12
6.3.6 Compilation
11.1.13 After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2).
70
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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 folder
specified by your lab instructor.
When a user selects writing option, you are required to take three inputs from the user: student
name (string type), student age (int type). After reading these data-items write to the file named
“student.txt”. Please note: write data using append mode otherwise previous information will be
lost.
Your program should have a search function. The search function should provide three options
for searching: by name, by age, or by registration number. After selection of the search option
by the user, please take input (name, age, or registration number) and search that student from the
file and display its record on the screen.
7.4 Testing
Practice Confirmation
Tasks
T1
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
72
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
10.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$
File Mode
Meaning
Flag
Append mode.
If the file already exists, its contents are preserved and all output is written to
ios::app
the end of the file. By default, this flag causes the file to be created if it does
not exist.
If the file already exists, the program goes directly to the end of it. Output may be
ios::ate written anywhere in the file.
Binary mode. When a file is opened in binary mode, information is written to or
ios::binary read from it in pure binary format. (The default mode is text.)
If the file does not already exist, this flag will cause the open function to fail. (The
ios::noreplace file will not be created.)
Input mode. Information will be read from the file. If the file does not exist, it
ios::in will not be created and the open function will fail.
If the file does not already exist, this flag will cause the open function to fail. (The
ios::nocreate
file will not be created.)
Output mode. Information will be written to the file. By default, the file’s contents
ios::out will be deleted if it already exists.
If the file already exists, its contents will be deleted (truncated). This is the default
ios::trunc
mode used by ios::out.
73
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-08
The protected Access Specifier and Types of Inheritance
74
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
So far, you have learned the importance and use of two (public and private) access specifiers within
class(es) of C++. You know that a class’s member functions are able to access class’s data fields
having public or private accessibility for all times. However, externally created object(s) can only
access public data members of that class and private data members are restricted to be accessed
outside the class. For example, consider the following class:
class Examp
{
private:
int attribute;
public:
void show()
{
cout<<attribute;
}
};
Any externally created instance (e.g. Obj) of class Examp would not be able to access data
member(s) directly while using the dot (.) operator. Hence, in the main() function, the statement
Obj.attribute is not legal but the statement Obj.show() is legal.
It is sufficient to know about public and private access specifiers/modifiers in the absence of
inheritance. However, in case of inheritance, sometimes it is required to access data member(s) of
base class in derived class(es) but not outside these classes. In this situation, you must make access
protected for that data member(s) rather than private or public. Protected access will ensure access
of data members only within inheritance hierarchy.
Another important use of access specifiers is their role in the inheritance process. Considering
access specification in C++, inheritance can be private, protected, or public. Each type of
inheritance has specific rules to access base class’s data member(s), which have been explained
below.
Public Inheritance:
Syntax: class Student: public Person
{
};
If a class is derived from a base class with public specifier, then all public/protected member(s) of
base class become public/protected member(s) of derived class. However, private member(s) of
base class are never accessible from derived class directly.
75
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Protected Inheritance:
Syntax: class Student: protected Person { };
If a class is derived from a base class with protected specifier, then all public/protected member(s)
of base class become protected member(s) of derived class. However, private member(s) of base
class are never accessible from derived class directly.
Private Inheritance:
Syntax: class Student: private Person { };
If a class is derived from a base class with private specifier, then all public/protected member(s)
of base class become private member(s) of derived class.
Relevant Lecture Readings:
● Lectures: 17, 18
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 372 - 428
4. Concept Map
Inheritance is one of the most important building blocks of OOP. The concept of reusable classes
is helpful to manage objects. You can create new classes (derived classes) that are able to inherit
certain attributes and behavior of their ancestor or base class(es). Prior to working with inheritance,
76
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
it was important to consider that data member(s) should have private access and only through
public member functions, you can access data members of a class. However, with inheritance, it
is sometimes required to have an intermediate level of accessibility to class’s data member(s) that
exists only within inheritance class hierarchy but not outside these classes.
C++ provides intermediate level of accessibility through protected access specifier. Data
member(s) of a base class with protected accessibility are only be directly accessible within base
class and all of its derived classes but not in other parts of the program. Nevertheless, you should
be careful while making data field(s) protected. Use protected access only where you think that
derived classes will use base class data field(s). The access of protected data members in the
derived classes make them less secure than private data members.
Moreover, access specifiers also play their role in the inheritance process. Considering access
specification in C++, inheritance can be private, protected, or public. The effects of access
specifiers in inheritance process on derived class’s member(s) are different as illustrated in Table
2.
Table 2: Inheritance access specifiers and their effect on derived class members
From the Rectangle class, derive a class named Cuboid that contains
● a data field named height in addition to length and width,
● two functions named setHeight and getHeight() to set and get value of height data field,
and
77
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
● a member function named cuboidArea() to calculate the area of a cuboid (length x width
x height)
Draw UML diagram for each class and show inheritance relationship between these classes.
Implement both classes and in the main() function, create an instance of ResearchCourse class.
Invoke appropriate functions to display all attribute values as well as the total fee for this particular
instance.
5.2.2 Task-2
Derive a class named SpacePoint to imagine a point in a three-dimensional space and has
following additional features:
● A data member Z of type integer to represent the z-coordinate of a point in space
● A no-argument constructor that constructs a point with coordinates (0,0,0)
78
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
● A constructor with three arguments that constructs a point with three specified coordinate
values
● An accessor function, which returns the value of data field Z
● A function named spaceDistance to return the distance between two points in the space
Implement both the classes and in the main() create two points with different dimensions and
invoke appropriate function to display the distance between these two points.
6.1 Tools
In this task, you are required to write a C++ code which would elaborate protected access specifier
concept. The following lines show the output of basic Inheritance concept with protected data
fields:
In the source file, which is created in the project “InheritanceSpecifier” write following C++ code:
79
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
80
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab07
81
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Write a main() function that instantiates objects of Convertible class and test the functionality of
all its member functions.
In the main() function, create objects of MobilePhone and Laptop classes and show the advantages
of using protected access specifier.
Derive a class named StaffService from the class CafeService that holds the following:
● Two data members i.e.
o serviceFee,
o the cabinNumber to which the service has been made
● A function named totalCharges that returns total cost of an order (including serviceFee +
price of food item(s) served)
● A parameterized constructor, which requires arguments for all of its own data fields as
well as for the data fields of base class
● A member function named display() to show all the details of an order including orderID,
price, and totalCharges
82
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
In the main() function, instantiate an object of class StaffService object and test the
implementation of both classes through this object.
7.4 Outcomes
After completing this lab, student will be able to understand the implementation and design of
inheritance as well as the use of protected access specifier in inheriting classes.
7.5 Testing
For all Practice Tasks, lab instructor must examine the implementation of all mentioned classes
the creation of instances of specified classes the invocation of specified functions
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
10.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
83
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-9
Function Overloading and Function Overriding
84
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
Earlier in Lab-08, you have already studied that a sub/derived class is able to access all non-private
data members and member functions of the base/parent class. Moreover, besides inheriting
attributes and behaviors from base class(es), the derived class also contains its own data members
and member functions.
Function overloading is the availability of various functions within a class that differ from each
other in function signature i.e. various functions share same name with different parameter types
or number of parameters. Inheritance is not necessarily required to overload functions within a
program.
On the other hand, in function overriding, there must exists inheritance relationship between
classes (i.e. base and derived) and functions’ signature are also required to be same in both parent
and child class(es). However, derived class(es) redefine function(s) having signature similar to
base class’s function(s).
Following code provides an example where both concepts (function overloading and overriding)
have been elaborated:
class Base
{
protected:
void myFunc()
{
cout<<"Base Class’ Function";
}
};
85
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
● At first, the class Derived shows function overloading while containing two functions differ
from each other in function signature (i.e. functions myFunc() and myFunc(int))
● Secondly, it also shows function overriding as it holds two function implementations with
same signature (i.e. besides myFunc() of its own, it also contains myFunc() inherited from
the Base class.
Relevant Lecture Readings:
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 188-193, 382-392
4. Concept Map
Function overloading and function overriding are the two key concepts of a number of modern
computer programming languages.
Overloaded functions provide specific functionalities while taking into account the type/number
of parameter(s) they receive and the fundamental advantage is the cleanliness of code. For
example, in the absence of overloading, a computer program may have several functions with
different names to calculate the area of a geometric shape as shown below:
class GeometricShape{
public:
86
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
class GeometricShape{
public:
int area(int sideLength);
int area(int length, int width);
int area(int side1, int side2, int side3);
};
On the other hand, function overriding is the ability of redefining a specific behavior (function) of
a base class within derived class(es). Besides the provisioning of a specific modified
implementation of a base class function, function overriding is used to perform runtime
polymorphism.
Derive a class named Car inherited from Automobile class and contains
● An additional data member named color
● A parameterized constructor to initialize its own data fields along with the inherited data
field
● Two functions named setColor and getColor to set and get the color of a Car object,
respectively
Derive a class named Limousine inherited from class Car and has its own functions (i.e.
setCurrentSpeed, getCurrentSpeed, setColor and getColor) to set/get speed and color for each of
its specific instance
87
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Draw UML diagram for each class and show inheritance relationship between these classes.
5.2.2 Task-2
Consider a class named Animal having typical function named eat that accepts a parameter of type
string. Three classes i.e. Herbivore, Carnivore, and Omnivore have been inherited from Animal
class. All these classes i.e. Herbivore, Carnivore, and Omnivore must have their own (overridden)
eat function.
a) Draw UML diagram for each class and show inheritance relationship between these
classes.
b) Implement all these classes
c) In the main function, create instances of Herbivore, Carnivore, and Omnivore classes and
invoke eat function with appropriate string parameter to display the liking of that animal
in eating.
6.1 Tools
Visual Studio 2017.
In this task, you are required to write a C++ code which would elaborate function overloading.
The following lines show the output of a basic function overloading concept:
6.3.1Writing Code
In the source file, which is created in the project “FunctionOverloading” write following C++
code:
88
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
89
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
90
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
6.3.2Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab09
In the main(), create instances of Shape Circle and Polygon classes. Invoke displayarea() with
shape object while passing references of Circle and Polygon instances.
91
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
● A member function named show() to display the details associated with an instance of this
class
Derive a class named WetLab from class Laboratory that includes
● data members no_of_microscopes and Scientist_name,
● respective mutator and accessor functions
● overriding function named input() to take input from user in all data members
● overriding function named show() to display the details associated with an instance of class
WetLab
From the Laboratory class, derive a class named DryLab that contains
● a data field named no_of_computers and Capacity
● Setters and getters
● an overriding function named input()
● overriding function named show() to display the details associated with an instance of this
class
Implement these classes and in the main() create instances of each class and test the functionality
of overridden member functions with these instances.
7.3 Outcomes
After completing this lab, student will be able to understand the difference between function
overloading and function overriding within a class or class hierarchies.
7.4 Testing
● For Practice Task 1, lab instructor must confirm the implementation of classes i.e.
GeometricShape, Rectangle, and Cuboid. With instances of each class, test the invocation
of proper overridden function.
● For Practice Task 2, lab instructor ensures the invocation of displayPrice() function with
the MusicalInstrument instance while receiving references of the instances of Flute and
Guitar classes.
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
Table 2: Evaluation of the Lab
92
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
10.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
93
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-10
Polymorphism in Object Oriented Programming
94
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
In general, polymorphism means ‘various shapes’ and within the context of an object-oriented
programming (OOP) language, it is the ability of an object to acquire various forms while
referencing various instances of the different classes in inheritance hierarchy. In OOP, a significant
characteristic is the type compatibility of a derived class pointer to its base class pointer. Taking
advantage of this useful aspect, polymorphism establishes a new way of programming.
A member function of a base class can be made a virtual function if it is probable to redefine
(override) this function in the derived class. The significance of making a function virtual becomes
evident when you want to invoke function of derived class from a pointer of base class referencing
derived class’s object. Following code provides an example of polymorphism mechanism in C++.
class Base
{
public:
virtual void func()
{
cout<<”Base Class Function”;
}
};
Upon calling func() with bPtr, Derived class func() will be invoked and output would be “Derived
Class Function”. In the absence of virtual keyword, func() of base would be called each time.
95
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Hence, it can be concluded that virtual keyword allow a pointer of base class to call appropriate
function of any of its derived class to whom it is referencing. In this way, each time a different
function will be invoked with the same function call. With polymorphism, compiler does not know
which function to call at compile and thus appropriate function call is deferred to runtime. At
runtime, the type of object that a base class pointer is pointing is recognized to call proper function.
This is known as dynamic or late binding.
Virtual keyword can also be used with destructors and classes. However, virtual keyword
possesses different meanings when used with destructor and classes as explained below.
Virtual Destructors:
In practice, it is always recommended to make the base class destructor as virtual. In the absence
of virtual keyword with base class destructor, upon deletion of any derived class’s object only
destructor of base class would be called.
class Base
{
protected:
void func()
{ cout<<”A Base Class Function”; }
};
class Derived1: public Base{ };
class Derived2: public Base{ };
class Derived3: public Derived1, public Derived2
{ };
In the code above, both (Derived1 and Derived2) classes contain a copy of func(), which is
inherited from class Base. Upon the invocation of func() with an object of Derived3 class,
compiler would be unable to decide which copy to use.
To overcome this situation, it is required to use virtual keyword with base class inheritance. Hence,
the above code would be implemented as
class Base
{
protected:
void func()
{ cout<<”A Base Class Function”; }
};
class Derived1: virtual public Base{ };
96
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
class Base
{
protected:
virtual void func() = 0;
};
Instantiation of an abstract class is not possible and you should override pure virtual function in
derived class(es).
97
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
Following encapsulation and inheritance, polymorphism is the third important capability of OOP
paradigm. The fundamental inspiration behind polymorphism is that of dynamic binding. In this
way, at compile time, compiler knows nothing about which function to call. On the contrary,
decision is made at runtime. Polymorphism helps programmer to make program in general rather
than specific. In simple words, it provides a single interface with different implementations.
Moreover, polymorphism facilitates program extensibility while permitting new derived classes
and functions to be added to an inheritance hierarchy without modifying application programs that
already utilize various interfaces of that inheritance hierarchy. However, for beginners, it is
difficult to grasp and implement the concept of polymorphism, dynamic binding, and abstract
classes.
Derive a class named CourseRecord inherited from Record class and contains
● Two additional data members i.e. marksCourse1 and marksCourse2
● A parameterized constructor to initialize its own data fields along with the inherited data
fields
● Two getter functions that return the value of marksCourse1 and marksCourse2,
respectively
Derive a class named CourseResult inherited from class CourseRecord and has
● A data field named totalMarks
● A function named marksObtained that returns totalMarks (i.e. marksCourse1 +
marksCourse2) of a student
● A member function named display to show rollNo, course1Name, course2Name,
marksCourse1, marksCourse2, and totalMarks
Draw UML diagram for each class and show inheritance relationship between these classes.
98
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
5.2.1 Task-1
Consider four classes i.e. Person, Staff, Professor, and Researcher with the following inheritance
hierarchy:
Class Researcher is derived from both Staff and Professor classes that are ultimately derived from
class Person.
Class Person has two attributes i.e. name and age and one member function display() to show its
attribute values.
Class Professor has two attributes i.e. courseID and courseName for the course he/she is teaching.
Class Researcher has additional attributes named labID and experimentNo for laboratory and
experiment under his supervision.
Draw UML diagram for each class and show inheritance relationship between these classes.
5.2.2 Task-2
Illustrate the implementation of classes that have been specified in Task-1 using C++ compiler in
a way that avoid diamond problem of multiple inheritance.
6.1 Tools
In this task, you are required to write a C++ code which would elaborate polymorphism concept.
The following lines show the output of a basic polymorphism concept:
99
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
In the source file, which is created in the project “Polymorphism” write following C++ code:
100
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Figure 1: Polymorphism
101
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the following
folder:
\\fs\assignments$\OOP\Lab10
A class named Birds inherits Animal class and adds fields representing
● A bool type variable flying
● Override function named show() to display values of its all attributes
A class named Reptiles inherits BOOK class and adds fields representing
● Length
● Override function named show() to display values of its all attributes
Write a main() function that instantiates objects of derived classes to access respective show()
function using dynamic binding.
102
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
In the main function, create instances of derived classes to access respective print() function using
dynamic binding.
From the Rectangle class, derive a class named Cuboid that contains
● a data field named height in addition to length and width,
● two functions named setHeight and getHeight() to set and get value of height data field,
and
● an overriding function named computeArea() to calculate the area of a cuboid (length x
width x height)
● overriding function named show() to display the details associated with an instance of class
Cuboid
In the main function, create instances of derived classes to access respective show() function using
dynamic binding.
103
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
7.4 Outcomes
After completing this lab, student will be able to implement the concepts of virtual functions,
dynamic binding, pure virtual function, and abstract classes.
7.5 Testing
● For Practice Task 1, it is required to check the assignment of derived class instances to
base class pointer. Moreover, (while considering the dynamic binding) test the invocation
of respective show() function.
● For Practice Task 2, it is required to check the assignment of derived class instances to
base class pointer. Moreover, (while considering the dynamic binding) test the invocation
of respective print() function.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
10.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lecures$\
104
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-11
Relationships in Object Oriented Programming
105
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
In OOP, various kinds of relationships (i.e. inheritance, association, aggregation, composition) exist
between various classes/objects.
Inheritance is modeled as is-a relationship. Inheritance exists between classes and the main goal of
inheritance is to make objects that would represent specialized versions of generalized original objects. For
example, a car is-a vehicle, manager is-an employee etc.
On the other hand, association and aggregation/composition represent uses-a and has-a relationship,
respectively between objects. It is based on the object-oriented design where an object can contain other
object(s). Association specifies that objects of different kinds are connected with each other and there exist
no ownership and lifecycle dependency. In advance, aggregation and composition are two types of
association representing weak and strong (whole-part) relationship between contained (whole) and owing
(part) objects. Therefore, aggregation and composition are other forms of code reusability along with
inheritance. Aggregation is a special kind of association represents ownership relationship between objects.
Composition is special kind of aggregation which represents ownership between objects along with the
existence of life-cycle dependency. A department-employees relationship is an example of aggregation
whereas university-departments relationship is an example of composition.
Following example explains the syntax for aggregation and composition in C++:
class Battery{ };
class Engine{ };
class Vehicle
{
private:
Battery *bat;
Engine *eng;
public:
Vehicle(Battery *b)
{
bat = b;
eng = new Engine();
}
~Vehicle()
{
delete eng;
}
};
Above example shows that aggregation exists between battery and vehicle because of the possession of
ownership but not life-cycle dependency. On the contrary, composition exists between vehicle and engine
because of the possession of ownership and life-cycle dependency.
Relevant Lecture Readings:
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 414- 420
106
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
Primarily two tasks are the part of each object-oriented design i.e. identification of object types within the
problem domain and relationship modeling between the existing object types. Three kinds of relationships
are usually exist between identified objects i.e.
The is-a relationship exhibits a relationship between an object of specific type to its general type. For
example, a bus is-a vehicle, an employee is-a person, circle is-a geometric shape etc. The is-a relationship
has been modeled in terms of inheritance that you have already studied in Lectures 15-18.
The uses-a relationship demonstrate that an object of one specific type uses an object of different type to
perform some activity. For example, a person uses-a wiper to wash bus window pane, a teacher uses-a
course to teach student, a cyclist uses-a pump in tire-pumping activity). The uses-a relationship can be
described as association between objects i.e. a teacher has association with student through a specific
course. Similarly, university has association with its departments through administration. In simple words,
association is a relationship between objects where exists no ownership and each object has its own
lifecycle. More specifically, association are of two types i.e. aggregation and composition that represents
has-a relationship between objects.
The has-a relationship represents a classical ownership of whole-part relationship. Sometimes an object of
one type contains an object of type e.g. a university has-a number of departments and ultimately a
department has a number of professors, a bus has-an engine, a bike has-a set of wheels etc. The has-a
relationship can be modeled as aggregation and composition.
107
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
A T20 is made up of at least 10 teams. Each cricket team is composed of 10 players, and one player captains
the team. A team has a name and a record. Players have a number and a position. Cricket teams play games
against each other. Each game has a score and a location. Teams are sometimes lead by a coach. A coach
has a level of accreditation and a number of years of experience, and can coach multiple teams. Coaches
and players are people, and people have names and addresses.
Draw UML diagram for each class and show inheritance, association, aggregation and composition
relationship between these classes.
Using C++ compiler, illustrate the implementation of classes that have been specified in section 5.1.1. Write
main() in a way that it clearly describes aggregation and composition relationships between objects of
implemented classes.
5.2.2 Task-2
Using C++ compiler, demonstrate the implementation of classes in a way that it proves inheritance
relationship between appropriate classes, association and aggregation/composition relationship between
objects of various classes in terms of ownership and lifecycle dependency.
6.1 Tools
Visual Studio 2017.
108
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
109
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
110
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab11
111
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
a) Draw UML diagram for each class and show inheritance, aggregation, and composition relationship
between these classes.
b) Implement all these classes while illustrating the concept of aggregation and composition in terms
of ownership and life-cycle.
7.3 Outcomes
After completing this lab, student will be able to implement the concepts of association, aggregation, and
composition in terms of ownership and life cycle of associated objects.
7.4 Testing
● For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly elaborated
the concept of aggregation and composition in terms of ownership and life cycle.
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
112
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
10.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
113
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-12
Function and Class Templates
114
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
In general, a template is used to represent a pattern. In programming, occasionally, a group of functions
and/or classes differ from each other simply in terms of parameter types or types of data members,
respectively. In these situations, templates are used to avoid redundant coding and can be practiced in two
ways i.e. with functions and with classes. In C++, templates facilitate the programmer to define a generic
function or class that is able to perform the same task with variables of different data types (including
objects of different classes). The syntax of writing a generic function in C++ is given as under:
You can call this function in different ways i.e. with parameters of types int, long, float, double as:
TemplateExample<int> TE1;
TemplateExample<double> TE2;
It is clear from above examples that prior to coding a function template or class template you have to provide
template definition statement starting with the keyword template. This template reserved word in C++
informs the compiler that programmer is going to define a function or class template. Further, the variable
with reserved word class or typename within angle brackets (< >) is known as the template argument. This
template argument is replaced with specific data type with each function call statement.
Relevant Lecture Readings:
● Lectures: 29, 30, 31
115
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
To deal with overloaded functions and various classes (that differ from each other in terms of the types of
data fields), C++ assists programmer to define generic functions and classes while using the concept of
templates. It is important to mention here that templates do not save the amount of memory to be used by
different functions or class objects. However, template approach (that is a very special kind of code
reusability) saves the time of writing multiple functions and classes with same logical task. In this way,
later on, modification(s) can be performed easily while changing code at one place instead of multiple
places.
The statement of template definition in C++ code by itself is not able to generate any code. Code generation
for a specific template function takes place at the time of function invocation. This is due to the fact that
upon function invocation compiler comes to know about the type to substitute template parameter. This is
known as instantiating the function template.
Concerning class templates in C++, it is important to point out here that C++ provides a powerful and
versatile collection of functions and classes for common data structures i.e. vector, stack, queue etc. This
collection of classes is known as Standard Template Library (STL). Functions and classes in STL provides
well-organized and extensible framework to develop certain applications.
116
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
A function named exchange that takes two values as its parameters and is responsible to swap these values.
It is required from you to implement exchange function as a template. In the main function, test the working
of exchange function by invoking it with parameters of int, long, double, and char data type.
5.1.2 Task-2
Make the class Calculator into a template and in this way, a user would be able to instantiate it using
different data types for the data members. In the main function, instantiate two objects of Calculator class
with data members of type integer and float, respectively and invoke all functions of class Calculator.
6.1 Tools
Visual Studio 2017.
In the source file, which is created in the project “TemplateExample” write following C++ code:
117
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab12
118
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
● A single data member as an array named list of size 10 to store certain elements
● A constructor to initialize queue with value 0 or 0.0 at all its indexes
● Three member functions i.e. sort() to sort the elements of the queue, max() that returns the
maximum value present in the queue, min() that returns the smallest value present in the queue,
and return_queue() that returns all the elements of the queue (in case of there being multiple
maximum and minimum values present in the queue, the member functions should return notify
the user of the number of times that value has been repeated in the queue and then return that value
to the main function).
In the main() function, create three objects with different data types of class queue and test the functionality
of member functions for various values of data members for these objects.
7.4 Outcomes
After completing this lab, student will be able to understand the use and working of function and class
templates in C++.
7.5 Testing
● Test cases for Practice Lab 1
119
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
area(5.0) 39.25
area(20.0,10.0) 600.0
● For Practice Lab 3, lab instructor should check the creation of three instances of List class while
each having an array of different data type. Moreover, check the required functionality of member
functions with these instances.
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
10.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
120
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-13
Static keyword in Object Oriented Programming
121
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
1. Introduction
There is an important exception to the rule that each object of a class has its own copy of all the data
members of the class. In certain cases, only one copy of a variable should be shared by all objects of a class.
A static data member is used for such propose.. Such a variable represents "class-wide" information (i.e., a
property of the class shared by all instances, not a property of a specific object of the class). The declaration
of a static member begins with keyword static.
In the above figure, consider Object1, Object2 and Object3 are three of a class. Each object has its own
private data members. The class has a static data member that is share among all the object of that class.
This data member has it own memory allocated that is separate from the memory allocated for each object
of that class.
Static keyword can be used as:
1. Variables in functions
Static variables when used inside function are initialized only once. They hold their value even through
function calls
122
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
2. Class objects
Objects declared static are allocated storage in static storage area. They have a scope till the end of program
Static objects are also initialized using constructors like other normal objects.
123
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
124
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
125
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
4. Concept Map
– [objectName].[public member function]
• e1.getCount();
– [Class name].[public mem.
Static data member – access
A public static data member can be access using any object of the class or class name
– [Object Name].[name of static variable]
• e1.count;
– [Class Name] .[name of static variable]
• Employee .count;
A private static member can be access using a public member function
– [objectName].[public member function]
• e1.getCount();
– [Class name].[public member function]
• Employee.getCount();
A static method is a method that can only access static data member of class. It cannot access
non static data member of that class.
126
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Create a SavingsAccount class. Use a static data member annualInterestRate to store the annual
interest rate for each of the savers. Each member of the class contains a private data member savingsBalance
indicating the amount the saver currently has on deposit. Provide member function
calculateMonthlyInterest that calculates the monthly interest by multiplying the balance by
annualInterestRate divided by 12; this interest should be added to savingsBalance. Provide a static
member function modifyInterestRate that sets the static annualInterestRate to a new value.
Write a driver program to test class SavingsAccount. Instantiate two different objects of class
SavingsAccount, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set the
annualInterestRate to 3 percent. Then calculate the monthly interest and print the new balances for each of
the savers. Then set the annualInterestRate to 4 percent, calculate the next month's interest and print the
new balances for each of the savers.
6.1 Tools
Visual Studio 2017.
127
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
In the source file, which is created in the project “StaticExample” write following C++ code:
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.
128
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab13
14.1 Create a Calculator class that has following methods: sum, multiply, divide, modulus , sin , cos , tan
The user should be able to call these methods without creating an object of Calculator class.
14.2 Create a class employee with data members as name, emp_id, salary and a static variable count. Count
should count total number of objects created for employee. In main() invoke setters and getters to take input
in attributes of employee.
7.3 Outcomes
After completing this lab, student will be able to implement the concepts static keyword.
7.4 Testing
● For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly elaborated
the concept of aggregation and composition in terms of ownership and life cycle.
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
Table 2: Evaluation of the Lab
129
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
10.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
130
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
LAB-14
Friend Functions and Friend Classes
131
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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
4. Concept Map
132
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
friend function you have to specify that a particular function is a friend function. This can be achieved through the
following syntax:
class second
{
private:
int mem1;
int mem2;
public:
friend void display( first, second ); //Friend function prototype
};
void display( 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;
display( obj1,obj2); //Simple calling. Cannot use the dot operator
}
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.
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.
133
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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
}
134
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
void main( )
{
first obj1;
second obj2;
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.
6.1 Tools
Visual Studio 2017.
135
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
Figure 1: The series class and the sum friend class. The display function is a friend function.
136
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
6.3.2 Compilation
15.1.1 After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\fs\assignments$\OOP\Lab06
137
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
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
a =1; proot= 1
b =2; nroot = -3
c =-3
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
138
Department of Computer Science/ Software Engineering
Faculty of Computing, Capital University of Science and Technology
assigned marks which will be evaluated by the instructor in the lab depending on the accomplishment of
the assigned tasks.
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
\\fs\lectures$\
139