Lab Manuals of OOP - New
Lab Manuals of OOP - New
Contribution
2
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Lab Outline
3
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
4
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
72.
Activity Time-
boxing 73.
Objective of the
Experiment 74.
Concept
Map 84.1
Reusability/ Modularity of
Code 84.2
Function Prototype and Function
Definition 84.3
Function Arguments and
Parameters 84.4
Returning a Value from a
Function 94.5
Pass by Value and Pass by
Reference 104.6
Pointers
114.7
Structures
124.7.1
How to define a structure in C++
programming? 124.7.2
How to define a structure
variable? 124.7.3
How to access members of a
structure? 134.7.4
Structure
Example 135.
Homework before
Lab 145.1
Problem solution
modeling 145.2
Practices from
home 145.2.1
Task
1 145.2.2
Task
2 146.
Procedure &
Tools 156.1
5
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Tools
156.2
Setting-up Visual Studio 2008
156.3
Walk-through Task
156.3.1
Writing
Code 156.3.2
Compilation
166.3.3
Executing the
Program 167.
Practice
Tasks 167.1
Practice Task 1
167.2
Practice Task 2
167.3
Practice Task 3
167.4
Out
comes 177.5
Testing
178.
Evaluation Task (Unseen) [Expected time = 60
mins] 189.
Evaluation
Criteria 1810.
Further
Readings 1810.1
Books
1810.2
Slides
18
6
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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
● Understand how values are passed by value and by reference to a function. Returning the values
thereafter.
● Use pointers and manipulate variables using pointers.
● Use an array with pointers in a function
● Understanding of structure
4. Concept Map
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.
8
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
out here that any variable that is created in a function body has a local scope and cannot be accessed outside
the function body. The data type of arguments must match the parameters of a function. In the following
example, variables a and b are parameters of the function addtwo( ).
void addtwo(int a, int b){
int c = a+b;
cout<< c;
}
Now suppose we are calling the same function from within the main().
void main (){
int x=3, y=4;
addTow(x, y);
}
For example the following function does not return a value hence the void keyword is used
void addtwo (int a, int b);{
int
c=a+b;
cout<<
c;
}
The following function returns an integer value hence the keyword int is used.
The value being returned can be displayed by using the following statement from where the function is
9
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
being c
cout<< addrow(x, y);
On the other hand pass by reference is an argument passing technique in which the function works with the
exact variable that is being passed as an argument. This means that even the smallest change in a parameter
will be exactly reflected in the arguments. This further implies that the arguments and the parameters are
tightly coupled.
10
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
4.6 Pointers
Pointers are special kind of variables that are allowed to hold the address of another variable. Because of
their pointing ability pointers are considered very powerful in C++. Pointers can hold the address of another
variable and this is called referencing the memory location. When we attempt to extract values from a
memory location then this is called dereferencing a pointer
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.
11
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Figure 2: The various operations that can be performed with a pointer. Output is also provided. Memory
addresses may be different depending on the hardware environment
In the code above first a simple integer variable is created. Then an integer pointer is created because we
intend to point to an integer variable. The pointer is then given the address of variable x by using the address
operator. Then we use the dereference operator (*) that directs us to the memory location where the pointer
is pointing to.
4.7 Structures
Structure is the collection of variables of different types under a single name for better visualization of
problem. Arrays is also collection of data but arrays can hold data of only one type whereas structure can
hold data of one or more types.
Here a structure person is defined which has three members: name, age and salary.
Output:
13
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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.
14
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
6.1 Tools
Visual Studio 2017.
In the code above note that the two functions use different mechanisms for passing/ using an array. You
can choose the method that suits your code/ situation. The size is passed in both functions because without
the size the functions can easily cross the array bounds. Hence passing the array size is a good practice.
6.3.2 Compilation
Write a program to find the power of a number if the base and exponent is provided in the main function.
Use pass by value mechanism to compute the power and return the results back to the main function then
display the result in main function.
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.
16
Lab 1: Formatting using Escape Sequences
3. deleteAStudent
4. searchAndDisplayAStudent
5. displayAllstudents
After that, create an array of 5 courses in main function. Create a menu in main function to enable user to
select and perform the operations we created above. Program must not exit until and unless user wants to
do so.
Sample Menu:
Main Menu
---------------
7.5 Testing
Test Cases for Practice Task-1
17
Lab 1: Formatting using Escape Sequences
T4
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
Text Book:
Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
18
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
19
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction 212. Activity Time boxing 213. Objective of the Experiment 214.
Concept Map 224.1 Object 224.2 Data Members 224.3 Member Function 224.4
Constant Member Function 234.5 Class 234.6 Encapsulation 245. Homework
before Lab 265.1 Problem solving Modelling 265.1.1 Problem description 265.2
Practices for home 265.2.1 Task-1 266. Procedure & Tolls 266.1 Tools
266.2 Setting-up Visual Studio 2008 266.3 Walkthrough Task
266.3.1 Writing Code 276.3.2 Compilation 286.3.3 Executing the
Program 287. 288. Practice Tasks 288.1 Practice Task 1 288.2 Practice Task 2
288.3 Out comes 288.4 Testing 299. Evaluation Task (Unseen) 2910.
Evaluation Criteria 2911. Further Readings 3011.1 Books 30
20
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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
21
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● Develop a basic class with a number of member functions
● Use a constant member function
● Separate the implementation section of a function
● Use the class objects and member functions to provide and extract data from an object
● Experiment with classes and objects
14.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.
22
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class myclass
{
int datamember;
void main( )
{
14.5 Class
A class is a co0llection of data members and member functions. A class is used to define an abstract data
type. This abstract data type is used in the construction of an object which is used to access all the data
members and member functions. A class has to be created before it can be used. Provided below is the
syntax for creating a class:
23
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
14.6 Encapsulation
Encapsulation is a very important design goal because of which OOP is preferred over conventional
programming. Encapsulation is a quality because of which data and function are stored in a single unit
commonly known as a class. This unit/ bundle ensure that the data is not openly accessible to the outer
world. The access is provided by the functions that are part of the unit/bundle. This means that the functions
work like doors in a room. You can prevent thieves from breaking in. Only those people can enter who
24
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
come through the door.
25
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
15.2.1 Task-1
Identify the data members and member functions for a submarine sandwich class. The class should have all
the relevant attributes and qualities required for a sandwich object. Try to be imaginative in your design.
For example consider various sauces, Mortadella, salads, cheese and other fillings etc.
16.1 Tools
Visual Studio 2008.
26
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Figure 1: Class for creating an arc with its relevant data members
27
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
16.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
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.
28
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
17.4 Testing
Now you need to perform the following test cases for all practice tasks mentioned above. The test cases
have been made available in Table 2.
The lab instructor will give you unseen task depending upon the progress of the class.
29
Capital University of Science and Technology, Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
3 7.1 Practice task 1 with Testing 10
4 7.2 Practice task 2 with Testing 20
5 8 Evaluation Tasks (Unseen) 15
6 Good Programming 10
Practices
Total Marks 80
20.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at: \\fs\lectures$
30
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
31
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
332.
Activity Time-
boxing 333.
Objective of the
Experiment 334.
Concept
Map 344.1
Access Specifiers – Public and Private
Access 344.2
Constructors
354.3
Destructors
355.
Homework before
Lab 365.1
Practices from
home 366.
Procedure &
Tools 376.1
Tools
376.2
Setting-up Visual Studio 2008
376.3
Walkthrough Task
376.3.1
Writing
Code 376.3.2
Compilation
386.3.3
Executing the
Program 387.
Practice
Tasks 387.1
Practice Task 1
387.2
Evaluation Task (Unseen)
408.
Evaluation
Criteria 40
32
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
21. Introduction
Programming that you studied in the previous semester does not strongly support programming practices
like encapsulation and data hiding. In fact these features are almost nonexistent in sequential programming.
Object Oriented Programming is purely based on these practices and enforces these practices through
various techniques. In this regard access specifiers play a very important role because they are the first line
of defense in secure programming. This lab is designed to teach three very basic yet essential concepts of
OOP namely access specifiers, constructor and destructors. Access specifiers provide a technique through
which we can restrict access to data members and member functions. After enforcing access it is important
to reduce our reliance on too many member functions. Constructors offer a very attractive and easy to
implement technique through which we can take steps call procedures whenever an object is created. The
use of constructors is preferred over the use of member functions because constructors are called
automatically and hence they can invoke further functions whereas simple member functions have to be
called sequentially and explicitly one by one every time an object is created. Similarly this lab also focuses
on the use of destructors that are called whenever an object goes out of scope. In this the lab the students
will be familiarized with the use of access specifiers, constructors and destructors.
Relevant Lecture Readings:
● Lectures: 3, 4, 5, 6
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 201-212
33
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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;
34
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
24.2 Constructors
A constructor is a function that is automatically called when an object is created. This function can exhibit
the regular behavior of any function except that it cannot return a value. The reason why constructors are
needed is that unlike regular functions which need to deliberately called, a constructor will be automatically
called when an object is created. Every constructor has a body from where we can call regular member
function a very important question which is often asked is that how does the compiler know that the
constructor function needs to be called automatically? The answer is very simple. A constructor is a function
that has the same name as the class. Whenever an object is created the compiler searches for a function
having the same name as the class i.e. the constructor. Given below is a sample code that shows the class
constructor. Generally the constructor is defined as public. Also the constructor can be overloaded like a
regular member function. An important point regarding a constructor is that it cannot return a value. In fact
writing the keyword void is strictly prohibited.
void main( )
{ myclass obj; }
24.3 Destructors
Constructors are designed to help initialize/ create an object. Destructors on the other hand do exactly the
opposite. Destructors are called whenever an object goes out of scope. When this happens it is necessary to
perform cleanup procedures especially when you have used dynamic memory or you have been working
with pointers in your code. The destructor function can be used to free up memory that you have allocated
or dereference pointers that were referenced. The rules for a destructor are as follows:
● They have the same name as the class just simply preceded by a tilde (~)
● They can take no arguments
● They cannot return anything, not even void
35
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class myclass
{
private:
int datamember; //Private data member public:
myclass( ); //Class constructor
{
cout<<”Hello you have called the class constructor”;
}
~myclass( ); //Class constructor
{ cout<<”Hello you have called the class destructor”; }
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();
}
36
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
26.1 Tools
Visual Studio 2017.
37
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
};
void main()
{ pizza obj; obj.display( ); }
26.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
38
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● PopSalon is charging Rs. 100 for small pack, Rs. 250 for medium sized pack, Rs. 500 for large
sized pack and Rs. 750 large size tin pack. Hence you will need a function to determine the size of
the pack and based on that the price. If a user enters option number other than the ones displayed,
your program should display an invalid input message and ask the user to re-enter the option
number.
● PopSalon allows its customers to purchase a gift wrapper with their popcorn. If the customer wants
to purchase the wrapper he will have to pay an additional Rs 50. This amount should be added to
the total amount payable by the user.
● If the customer asks for chocolate sauce, caramel sauce, or melted cheese as an additional topping
then he will have to pay an additional amount of Rs. 50, Rs. 30 and, Rs. 60 respectively. Design a
function that will be called if the customer chooses an additional topping.
● The program should show a menu that asks the customer for his requirements and then displays the
final payable amount with full details about the flavor, the size of the pack and details regarding
any additional toppings.
● For service quality inspection and monthly product promotions, the program should ask the user to
enter his/her contact details including name, mobile number and email address, and select between
the options good, neutral and bad against the quality of the service provided.
● In the end create a class destructor that displays a thank you message to the user. Design your
program using sound OOP practices. Carefully determine the data members, member functions,
access specifiers, activities to be performed in the constructor. Make sure that you use good naming
conventions in your code. A good design can earn you higher marks.
27.2 Outcome:
After completing this lab, students will be able to design a class that correctly implements class members
by observing access specifiers. The students will also be familiar with the use of a constructor and
destructor.
27.3 Testing
Test Cases for Practice Task-1
39
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
The lab instructor will give you unseen task depending upon the progress of the class.
40
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
29.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
29.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\fs\lectures$
41
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
42
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
452.
Activity Time
boxing 453.
Objective of the
Experiment 454.
Concept
Map 454.1
Function
Overloading 454.2
Constructor Overloading – Parameterized and Nullary
Constructors 464.3
Copy
Constructors 475.
Home Work before
Lab 475.1
Practices from
home 476.
Procedure &
Tools 476.1
Tools
476.2
Setting-up Visual Studio 2008
476.3
Walkthrough Task
476.3.1
Writing Code
486.3.2
Compilation
496.3.3
497.
Practice
Tasks 497.1
Practice Task 1
507.2
Practice Task 2
517.3
Outcomes
527.4
Testing
528.
43
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
44
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
45
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
of parameters, type of parameters or the order of parameters. For example in the function prototypes below the function
fun( ) has been overloaded and its different flavours are presented.
int fun (int, float, float);
int fun (int, float);
int fun (float, float, int);
It is important to highlight here that if two functions have a different return type then it does not mean that they are
overloaded. For a function to be overloaded it is necessary for the function to exhibit changes in the parameters.
46
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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.
35.1 Tools
Visual Studio 2017.
47
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class student
{
private:
string name;
int age;
public:
Figure 1: The student class demonstrating the use of a parameterized and nullary constructor. Also note
the default copy constructor being used
35.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.
49
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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,
50
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
the last position must contain an alphabetic character to indicate possible truncation, and if there is a given
name, the two fillers and at least one character of it must be included.
● The format of the second row is:
Position Lengt Characters Meaning
s h
1–9 9 alpha+num+< Passport number
10 1 numeric Check digit over digits 1–9
11–13 3 alpha+< Nationality (ISO 3166-1 alpha-3 code with modifications)
14–19 6 numeric Date of birth (YYMMDD)
20 1 num Check digit over digits 14–19
21 1 alpha+< Sex (M, F or < for male, female or unspecified)
22–27 6 numeric Expiration date of passport (YYMMDD)
28 1 numeric Check digit over digits 22–27
29–42 14 alpha+num+< Personal number (may be used by the issuing country as it
desires)
43 1 numeric Check digit over digits 29–42 (may be < if all characters are <)
44 1 numeric Check digit over digits 1–10, 14–20, and 22–43
● The check digit calculation is as follows: each position is assigned a value; for the digits 0 to 9 this is the
value of the digits, for the letters A to Z this is 10 to 35, for the filler < this is 0. The value of each position
is then multiplied by its weight; the weight of the first position is 7, of the second it is 3, and of the third it
is 1, and after that the weights repeat 7, 3, 1, and so on. All values are added together and the remainder of
the final value divided by 10 is the check digit.
Write a program that uses accepts a given Machine Readable Code and using a class stores the following 11 parts of
a passport separately after extraction as private data members:
1. Full Name
2. Passport Number
3. Nationality
4. Gender
5. Date of Birth
6. Country of Issuance (Passport Issuance)
7. Date of Issuance (Passport Issuance)
8. Date of Expiry
9. Citizenship Number
10. Passport Type
Create setters and getters for all the member variables and a public method named display to display the all the data
members.
Create three constructors as follows:
1. A nullary constructor that initializes the Citizenship Number as “*****-*******-*”.
2. A parameterized constructor that accepts First Name and Second Name and concatenates them into the data
member “Full Name” in its body.
3. A parameterized constructor that will set Gender, Nationality, and Passport Number as sent in parameters.
51
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● First object is initialized with default constructor. The values are then set by calling the setters
● Second object is initialized with the constructor that accepts three arguments.
● Third object is initialized with the constructor that accepts four arguments.
36.3 Outcomes
After completing this lab, students will be able to construct a class object by using parameterized
constructors. The students will also be familiar with the use of a constructor and destructor.
36.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Using Nullary constructor Your Data is:
Full Name = ALMEERA RAZA
Gender = F
Nationality= PAK
Issuance Date= 12-12-12
Expiry Date=12-12-25
Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=RAZA
Using parameterized constructor (string, string) Your Data is:
FirstName=” ALMEERA” Full Name = ALMEERA ZAHID
LastName=”ZAHID” Gender = F
Nationality= PAK
Issuance Date= 12-12-12
Expiry Date=12-12-25
Country of Issuance= PAK
Citizenship Number= 98858-8538674-0
DOB= 12-04-99
Passport Number= YR898395
Father Name=ZAHID
Using parameterized constructor (char, string, string) Your Data is:
Gender = ‘F’ Full Name = ALMEERA ZAHID
Nationality = “PAK” Gender = F
Passport_Numer= Nationality= PAK
Issuance Date= 12-12-12
52
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
53
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
6 Good Programming 10
Practices
Total Marks 100
39.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
39.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
54
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
55
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
582.
Activity Time
boxing 583.
Objective of the
Experiment 584.
Concept
Map 594.1
Creating a customized copy
constructor 594.2
Shallow Copy
Constructor 594.3
Deep Copy
Constructor 604.4
Working with
Arrays 615.
Home Work Before
Lab 635.1
Practices from
Home 646.
Procedure &
Tools 646.1
Tools
646.2
Setting-up Visual Studio
2008 646.3
Walkthrough
Task 647.
Practice
Tasks 657.1
Practice Task
1 667.2
Practice Task
2 667.3
Outcomes
667.4
Testing
668.
Evaluation Task
(Unseen) 679.
Evaluation
Criteria 6710.
56
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Further
Reading 6810.1
Books
6810.2
Slides
68
57
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
58
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
59
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the above code when object obj1 is created the nullary constructor is called and hence values 10 and 20
are allocated to data members a and b respectively. Now when object obj2 is being created obj1 is passed
to the copy constructor as an argument. While creation of obj2 control is never shifted to the basic
constructor because we are attempting to make a new object by copying.
60
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Memory
Copy of
Object Object
1 1
(a)
Memory
Copy of
Object Object
1 1
(b)
Figure 1: The effect of copy constructors on a pointer data member (a) using shallow copy (b) Using deep
copy
In the code snippet below a deep copy constructor has been provided that creates a copy of a char array.
The data member len is being used to hold the length of the array.
When working with copy constructors it is important to remember that the copy constructor function
prototype is the same for both shallow copy and deep copy. Hence the difference lies in the fact that dynamic
data members are being handled or not. To determine if a deep copy or shallow copy constructor is being
used you have to study the copy constructor body.
61
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
is that they provide contiguous memory locations that can be accessed with a simple iterative mechanism
like loops. When it comes to classes we have many options relating to arrays. All the possibilities related
to arrays are part of this lab.
Given below is a class named example that contains a simple (static) floating point array “a”. This array
can be initialized with a constructor or with a simple member function as follows.
class example
{
private:
float a[10]; //array as a data member
public:
example() // normal constructor
{
for(int i=0; i<=9;i++)
{
a[i]=0; // put the value 0 in all
locations
}
}
// other stuff
};
Given below is a class named example that contains a dynamic floating point array “a”. This array can be
initialized with a constructor or with a simple member function as follows. Since this code works with a
dynamic array therefore the size of the array can be provided at run time. In this particular code since the
size is not passed there may be a possibility that the programmer crosses the array boundary.
class example
{
private:
float *a; //Dynamic array as a data member
public:
example() // normal constructor
{
a=new float[10]; //size can be passed from main to
constru
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.
63
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class english
{
private:
string sentence;
int size;
public:
example()
{
cout<<"Enter your sentence: ";
getline(cin,sentence);
size=9;
size=sentence.length();
}
example (example & tempobj)
{
size = tempobj.size;
sentence=tempobj.sentence;
}
void showall()
{
cout<<"\nSentence: "<<sentence;
cout<<"\nCharacters: "<<size<<"\n";
} };
64
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
int main( )
{
english obj1;
english obj2=obj1;
cout<<"Object one contains data";
obj1.showall();
cout<<"Copied object contains data";
obj2.showall();
return 0;
}
Figure 1: The “english” class demonstrating the use of a constructor and a copy constructor.
45.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.
65
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
finish the tasks in the required time. When you finish them, put these tasks in the following folder:
\\dataserver\assignments$\OOP\Lab05
46.3 Outcomes
After completing this lab, students will be able to conveniently use a copy constructor in both deep copy
and shallow copy mode. Further the students will have the ability to comfortably use arrays in their various
forms both inside and outside the class.
46.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Title = Interstellar After selective copying only the permanent attributes
Air_Date = October 26th,2014 contain values.
66
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
67
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Testing
4 7.2 Practice task 2 with 20
Testing
5 8 Evaluation Tasks 25
(Unseen)
6 Good Programming 10
Practices
Total Marks 100
49.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
49.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
68
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
69
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
69
2.Activity Time-
boxing 69
3.Objective of the
Experiment 70
4. Concept
Map 70
4.1 Permanent
Storage 70
4.2 Data
Retrieval 71
6.Procedure &
Tools 71
6.1 Tools
71
6.2Setting-up Visual Studio 2017
71
6.3Walkthrough Task
71
7. Practice
Tasks 74
7.1Practice Task 1
74
7.2 Out
comes 75
7.3 Testing
75
70
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
9. Evaluation
Criteria 75
71
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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.
72
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
73
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
situation, filling help us to read data from the permanent storage for example a hard-disk, and
applications can be launched with correct starting state.
55.1 Tools
Visual Studio 2017.
74
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
55.3.3 Compilation
▪ After writing the code, compile your code according to the guidelines
mentioned in Lab-1 (section 6.3.2)
75
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Read the student information which was written in the previous program example. After reading
the data from “student.txt”, output it to the screen. For reading the file, write following C++ code
(as shown in the Figure 3). This code opens the “student.txt” file for reading student information
and outputs on the screen.
76
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
55.3.6 Compilation
▪ After writing the code, compile your code according to the guidelines
mentioned in Lab-1 (section 6.3.2).
77
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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.
78
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
56.4 Testing
Practice Confirmation
Tasks
T1
79
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
59.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.
80
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
81
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
842.
Activity Time
Boxing 853.
Objective of the
Experiment 854.
Concept
Map 865.
Homework before
Lab 865.1
Problem Solution
Modeling 865.2
Practices from
Home 876.
Procedure &
Tools 886.1
Tools
886.2
Setting-up Visual Studio 2017
886.3
Walkthrough Task
887.
Practice
Tasks 907.1
Practice Task 1
907.2
Practice Task 2
917.3
Practice Task 3
917.4
Outcomes
927.5
Testing
928.
Evaluation Task (Unseen)
929.
Evaluation
Criteria 9210.
Further
Reading 9310.1
Books
9310.2
Slides
82
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
93
83
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class Examp
{
private:
int attribute;
public:
void show()
{
cout<<attribute;
}
};
Any externally created instance (e.g. Obj) of class Examp would not be able to access data
member(s) directly while using the dot (.) operator. Hence, in the main() function, the statement
Obj.attribute is not legal but the statement Obj.show() is legal.
It is sufficient to know about public and private access specifiers/modifiers in the absence of
inheritance. However, in case of inheritance, sometimes it is required to access data member(s) of
base class in derived class(es) but not outside these classes. In this situation, you must make access
protected for that data member(s) rather than private or public. Protected access will ensure access
of data members only within inheritance hierarchy.
Another important use of access specifiers is their role in the inheritance process. Considering
access specification in C++, inheritance can be private, protected, or public. Each type of
inheritance has specific rules to access base class’s data member(s), which have been explained
below.
Public Inheritance:
Syntax: class Student: public Person
{
};
84
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
If a class is derived from a base class with public specifier, then all public/protected member(s) of
base class become public/protected member(s) of derived class. However, private member(s) of
base class are never accessible from derived class directly.
Protected Inheritance:
Syntax: class Student: protected Person { };
If a class is derived from a base class with protected specifier, then all public/protected member(s)
of base class become protected member(s) of derived class. However, private member(s) of base
class are never accessible from derived class directly.
Private Inheritance:
Syntax: class Student: private Person { };
If a class is derived from a base class with private specifier, then all public/protected member(s)
of base class become private member(s) of derived class.
Relevant Lecture Readings:
● Lectures: 17, 18
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 372 - 428
85
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● understand the use of protected access specifier with class’s data members
● understand public, private, and protected types of inheritance
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
86
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
From the Rectangle class, derive a class named Cuboid that contains
● a data field named height in addition to length and width,
● two functions named setHeight and getHeight() to set and get value of height data field,
and
● a member function named cuboidArea() to calculate the area of a cuboid (length x width
x height)
Draw UML diagram for each class and show inheritance relationship between these classes.
Implement both classes and in the main() function, create an instance of ResearchCourse class.
Invoke appropriate functions to display all attribute values as well as the total fee for this particular
instance.
5.2.2 Task-2
87
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Derive a class named SpacePoint to imagine a point in a three-dimensional space and has
following additional features:
● A data member Z of type integer to represent the z-coordinate of a point in space
● A no-argument constructor that constructs a point with coordinates (0,0,0)
● A constructor with three arguments that constructs a point with three specified coordinate
values
● An accessor function, which returns the value of data field Z
● A function named spaceDistance to return the distance between two points in the space
Implement both the classes and in the main() create two points with different dimensions and
invoke appropriate function to display the distance between these two points.
65.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:
88
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
89
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.
90
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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
91
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the main() function, instantiate an object of class StaffService object and test the
implementation of both classes through this object.
66.4 Outcomes
After completing this lab, student will be able to understand the implementation and design of
inheritance as well as the use of protected access specifier in inheriting classes.
66.5 Testing
For all Practice Tasks, lab instructor must examine the implementation of all mentioned classes
the creation of instances of specified classes the invocation of specified functions
67. Evaluation Task (Unseen) [Expected Time = 50 mins for all tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
92
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Practices
Total Marks 100
69.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
69.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
93
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
94
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
962.
Activity Time
Boxing 973.
Objective of the
Experiment 974.
Concept
Map 985.
Homework before
Lab 985.1
Problem Solution
Modeling 985.2
Practices from
home 996.
Procedure &
Tools 1006.1
Tools
1006.2
Setting-up Visual Studio 2017
1006.3
Walkthrough Task
1007.
Practice
Tasks 1027.1
Practice Task 1
1027.2
Outcomes
1047.3
Testing
1048.
Evaluation Task (Unseen)
1059.
Evaluation
Criteria10510. Further
Reading 10510.1
Books
10510.2
Slides
105
95
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● Single Inheritance: a single child class derived from a single base class
● Hierarchical Inheritance: multiple child classes derived from a single base class
● Multi-level Inheritance: a single derived class inherited from another derived class
● Multiple Inheritance: a single derived class inherited from more than one base classes
● Hybrid Inheritance: any legal combination of more than one type of inheritance
In particular, the main focus of this lab is concerned with the understanding of multi-level and
multiple inheritance. Multi-level represents the scenario of inheriting attributes and behavior of a
class that is already inheriting attributes and behaviors from other class(es). The syntax of writing
C++ code to implement multi-level class hierarchy is given as under:
class X
{
// code statements go here
};
class Y: public X
{
//code statements go here
};
class Z: public Y
{
//code statements go here
};
...
Multiple Inheritance represents where a single class inherits attributes and behaviors from more
than one class. The syntax to write C++ code for multiple inheritance is given as under:
class X
96
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
{
// code statements go here
};
class Y
{
//code statements go here
};
class Z: public X, public Y
{
//code statements go here
};
97
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
A person can be an employee or a student. An employee may have rights of admin officer or of
academic officer. These class hierarchies represent multi-level inheritance. However, a Dean or
Head of Department (HOD) may have rights to modify the status already defined by an admin or
academic officer. This type of relationship between classes is an example of multiple inheritance.
C++ facilitates users while supporting the implementation of both multi-level and multiple
inheritance. There is no limitation on the number of levels in multi-level inheritance and there is
no limitation on the number of parent classes from which a child can be derived. Nevertheless, as
a good practice, it is recommended to restrict levels and number of base classes to two in multi-
level and multiple inheritance.
Draw UML diagram for each class and show inheritance relationship between these classes.
Consider the problem description of section 5.1.1 of this lab that deals with three classes i.e. Staff,
Professor, and VisitingProfessor. Implement all these classes and in the main function, create an
object of class VisitingProfessor and invoke its member function display to show total income of
a visiting professor.
5.2.2 Task-2
Draw UML diagram for each class and show inheritance relationship between these classes.
Moreover, illustrate the implementation of these classes in C++.
99
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the source file, which is created in the project “MultipleInheritance” write following C++ code:
#include<iostream>
using namespace std;
class Student
{
protected:
int registrationNum,marks1,marks2;
public:
void getMarks()
{
cout<<"Enter the Registration number: ";
cin>>registrationNum;
cout<<"Enter the marks: ";
cin>>marks1;
cin>>marks2;
}
};
class SportActivity
{
protected:
int sportsmarks;
public:
void getSportsMarks()
{
cout<<"\nEnter the marks for sports: ";
100
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
cin>>sportsmarks;
}
};
class MarksStatment:public Student,public SportActivity
{
int totalMarks,averageMarks;
public:
void ShowStatement()
{
totalMarks=(marks1+marks2+sportsmarks);
averageMarks=totalMarks/3;
cout<<"\ntRegistrattion Number: "<<registrationNum<<"\nTotal marks: "
<<totalMarks;
cout<<"\nAvergae marks : "<<averageMarks;
}
};
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.
101
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
102
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
o Two functions i.e. setJobTitle(employee) and getJobTitle(employee) to set and get job
title of an employee.
● Class Student has
o Two attributes i.e. studentID and enrolledSemester
o A four-argument constructor to initialize its data members (including inherited data
members)
o A function named display() to show the values of all attributes (including inherited
attributes)
● Only an instance of class DeanHOD should be able to modify values for employeeID,
designation of an employee, ID and name of a particular course.
Implement all these classes and within the main function, create instances of all classes (except
class Employee) and test the described working of all these classes.
Implement all class definitions with their respective constructors to initialize all data members
and functions to compute the total income of an employee. In the main() function, create an
instance of both classes (i.e. HourlyEmployee and PermanentEmployee) and test the working of
103
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Derive two classes from the BankAccount class i.e. CurrentAccount and the SavingsAccount.
Both classes (CurrentAccount and SavingsAccount) inherit all attributes/behaviors from the
BankAccount class. In addition, followings are required to be the part of both classes
● Appropriate constructors to initialize data fields of base class
● A function named amountWithdrawn(amount) to withdraw certain amount while taken
into account the following conditions
o While withdrawing from current account, the minimum balance should not
decrease Rs. 5000
o While withdrawing from savings account, the minimum balance should not
decrease Rs. 10,000
● amountDeposit(amount) to deposit amount in the account
In the main() function, create instances of derived classes (i.e. CurrentAccount and
SavingsAccount) and invoke their respective functions to test their working.
76.4 Outcomes
After completing this lab, student will be able to understand the implementation and design of
Multi-level and Multiple Inheritance in C++.
76.5 Testing
● For Practice Task 1, while inspecting implementation of classes, lab instructor must ensure
that student has taken hold the concept of multi-level and multiple inheritance.
Furthermore, it is required to check the invocation of all functions with the created
instances of all mentioned classes.
104
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
77. Evaluation Task (Unseen) [Expected Time = 55 mins for all tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
79.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
79.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
105
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
106
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
1082.
Activity Time
Boxing 1093.
Objective of the
Experiment 1094.
Concept
Map 1095.
Homework before
Lab 1105.1
Problem Solution
Modeling 1105.2
Practices from
home 1116.
Procedure &
Tools 1116.1
Tools
1116.2
Setting-up Visual Studio 2017
1116.3
Walkthrough Task
1127.
Practice
Tasks 1147.1
Practice Task 1
1147.2
Practice Task 2
1147.3
Outcomes
1157.4
Testing
1158.
Evaluation Task (Unseen)
1169.
Evaluation
Criteria 11610.
Further
Reading 11610.1
Books
11610.2
Slides
116
107
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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";
}
};
108
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
}
};
109
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Overloaded functions provide specific functionalities while taking into account the type/number
of parameter(s) they receive and the fundamental advantage is the cleanliness of code. For
example, in the absence of overloading, a computer program may have several functions with
different names to calculate the area of a geometric shape as shown below:
class GeometricShape{
public:
int squareArea(int sideLength);
int reactangleArea(int length, int width);
int triangleArea(int side1, int side2, int side3);
};
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
110
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Derive a class named Limousine inherited from class Car and has its own functions (i.e.
setCurrentSpeed, getCurrentSpeed, setColor and getColor) to set/get speed and color for each of
its specific instance
Draw UML diagram for each class and show inheritance relationship between these classes.
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.
111
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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:
In the source file, which is created in the project “FunctionOverloading” write following C++
code:
112
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
113
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.
In the main(), create instances of Shape Circle and Polygon classes. Invoke displayarea() with
shape object while passing references of Circle and Polygon instances.
114
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
From the Laboratory class, derive a class named DryLab that contains
● a data field named no_of_computers and Capacity
● Setters and getters
● an overriding function named input()
● overriding function named show() to display the details associated with an instance of this
class
Implement these classes and in the main() create instances of each class and test the functionality
of overridden member functions with these instances.
86.3 Outcomes
After completing this lab, student will be able to understand the difference between function
overloading and function overriding within a class or class hierarchies.
86.4 Testing
● For Practice Task 1, lab instructor must confirm the implementation of classes i.e.
GeometricShape, Rectangle, and Cuboid. With instances of each class, test the invocation
of proper overridden function.
● For Practice Task 2, lab instructor ensures the invocation of displayPrice() function with
the MusicalInstrument instance while receiving references of the instances of Flute and
Guitar classes.
115
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
The lab instructor will give you unseen task depending upon the progress of the class.
89.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
89.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
116
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
117
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
1202.
Activity Time
Boxing 1223.
Objective of the
Experiment 1234.
Concept
Map 1235.
Homework before
Lab 1235.1
Problem Solution
Modeling 1235.2
Practices from
home 1246.
Procedure &
Tools 1256.1
Tools
1256.2
Setting-up Visual Studio 2017
1256.3
Walkthrough Task
1257.
Practice
Tasks 1277.1
Practice Task 1
1277.2
Practice Task 2
1287.3
Practice Task 3
1287.4
Outcomes
1297.5
Testing
1298.
Evaluation Task (Unseen)
1299.
Evaluation
Criteria 12910.
Further
Reading 13010.1
Books
13010.2
Slides
118
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
130
119
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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”;
}
};
120
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
bPtr = &dev;
bPtr->func();
}
Upon calling func() with bPtr, Derived class func() will be invoked and output would be “Derived
Class Function”. In the absence of virtual keyword, func() of base would be called each time.
Hence, it can be concluded that virtual keyword allow a pointer of base class to call appropriate
function of any of its derived class to whom it is referencing. In this way, each time a different
function will be invoked with the same function call. With polymorphism, compiler does not know
which function to call at compile and thus appropriate function call is deferred to runtime. At
runtime, the type of object that a base class pointer is pointing is recognized to call proper function.
This is known as dynamic or late binding.
Virtual keyword can also be used with destructors and classes. However, virtual keyword
possesses different meanings when used with destructor and classes as explained below.
Virtual Destructors:
In practice, it is always recommended to make the base class destructor as virtual. In the absence
of virtual keyword with base class destructor, upon deletion of any derived class’s object only
destructor of base class would be called.
class Base
{
protected:
void func()
{ cout<<”A Base Class Function”; }
};
class Derived1: public Base{ };
class Derived2: public Base{ };
class Derived3: public Derived1, public Derived2
{ };
In the code above, both (Derived1 and Derived2) classes contain a copy of func(), which is
inherited from class Base. Upon the invocation of func() with an object of Derived3 class,
compiler would be unable to decide which copy to use.
To overcome this situation, it is required to use virtual keyword with base class inheritance. Hence,
the above code would be implemented as
121
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class Base
{
protected:
void func()
{ cout<<”A Base Class Function”; }
};
class Derived1: virtual public Base{ };
class Derived2: virtual public Base{ };
class Derived3: public Derived1, public Derived2
{ };
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).
122
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Derive a class named CourseRecord inherited from Record class and contains
123
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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.
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
124
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
95.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:
In the source file, which is created in the project “Polymorphism” write following C++ code:
125
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Figure 1: Polymorphism
126
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
6.3.2. Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any
errors and warnings that are present in your code.
A class named Birds inherits Animal class and adds fields representing
● A bool type variable flying
● Override function named show() to display values of its all attributes
A class named Reptiles inherits BOOK class and adds fields representing
● Length
● Override function named show() to display values of its all attributes
127
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Write a main() function that instantiates objects of derived classes to access respective show()
function using dynamic binding.
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
128
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the main function, create instances of derived classes to access respective show() function using
dynamic binding.
96.4 Outcomes
After completing this lab, student will be able to implement the concepts of virtual functions,
dynamic binding, pure virtual function, and abstract classes.
96.5 Testing
● For Practice Task 1, it is required to check the assignment of derived class instances to
base class pointer. Moreover, (while considering the dynamic binding) test the invocation
of respective show() function.
● For Practice Task 2, it is required to check the assignment of derived class instances to
base class pointer. Moreover, (while considering the dynamic binding) test the invocation
of respective print() function.
The lab instructor will give you unseen task depending upon the progress of the class.
129
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
99.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
99.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lecures$\
130
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
131
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
1332.
Activity Time
Boxing 1343.
Objective of the
Experiment 1344.
Concept
Map 1345.
Homework before
Lab 1355.1
Problem Solution
Modeling 1355.2
Practices from
home 1356.
Procedure &
Tools 1366.1
Tools
1366.2
Setting-up Visual Studio 2017
1366.3
Walkthrough Task
1367.
Practice
Tasks 1387.1
Practice Task 1
1387.2
Practice Task 2
1397.3
Outcomes
1397.4
Testing
1398.
Evaluation Task (Unseen)
1399.
Evaluation
Criteria 14010.
Further
Reading 14010.1
Books
14010.2
Slides
140
132
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Inheritance is modeled as is-a relationship. Inheritance exists between classes and the main goal of
inheritance is to make objects that would represent specialized versions of generalized original objects. For
example, a car is-a vehicle, manager is-an employee etc.
On the other hand, association and aggregation/composition represent uses-a and has-a relationship,
respectively between objects. It is based on the object-oriented design where an object can contain other
object(s). Association specifies that objects of different kinds are connected with each other and there exist
no ownership and lifecycle dependency. In advance, aggregation and composition are two types of
association representing weak and strong (whole-part) relationship between contained (whole) and owing
(part) objects. Therefore, aggregation and composition are other forms of code reusability along with
inheritance. Aggregation is a special kind of association represents ownership relationship between objects.
Composition is special kind of aggregation which represents ownership between objects along with the
existence of life-cycle dependency. A department-employees relationship is an example of aggregation
whereas university-departments relationship is an example of composition.
Following example explains the syntax for aggregation and composition in C++:
class Battery{ };
class Engine{ };
class Vehicle
{
private:
Battery *bat;
Engine *eng;
public:
Vehicle(Battery *b)
{
bat = b;
eng = new Engine();
}
~Vehicle()
{
delete eng;
}
};
133
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Above example shows that aggregation exists between battery and vehicle because of the possession of
ownership but not life-cycle dependency. On the contrary, composition exists between vehicle and engine
because of the possession of ownership and life-cycle dependency.
Relevant Lecture Readings:
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 414- 420
The is-a relationship exhibits a relationship between an object of specific type to its general type. For
example, a bus is-a vehicle, an employee is-a person, circle is-a geometric shape etc. The is-a relationship
has been modeled in terms of inheritance that you have already studied in Lectures 15-18.
The uses-a relationship demonstrate that an object of one specific type uses an object of different type to
perform some activity. For example, a person uses-a wiper to wash bus window pane, a teacher uses-a
course to teach student, a cyclist uses-a pump in tire-pumping activity). The uses-a relationship can be
described as association between objects i.e. a teacher has association with student through a specific
134
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
course. Similarly, university has association with its departments through administration. In simple words,
association is a relationship between objects where exists no ownership and each object has its own
lifecycle. More specifically, association are of two types i.e. aggregation and composition that represents
has-a relationship between objects.
The has-a relationship represents a classical ownership of whole-part relationship. Sometimes an object of
one type contains an object of type e.g. a university has-a number of departments and ultimately a
department has a number of professors, a bus has-an engine, a bike has-a set of wheels etc. The has-a
relationship can be modeled as aggregation and composition.
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.
135
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
5.2.2 Task-2
Using C++ compiler, demonstrate the implementation of classes in a way that it proves inheritance
relationship between appropriate classes, association and aggregation/composition relationship between
objects of various classes in terms of ownership and lifecycle dependency.
136
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
137
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
138
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
a) Draw UML diagram for each class and show inheritance, aggregation, and composition relationship
between these classes.
b) Implement all these classes while illustrating the concept of aggregation and composition in terms
of ownership and life-cycle.
106.3 Outcomes
After completing this lab, student will be able to implement the concepts of association, aggregation, and
composition in terms of ownership and life cycle of associated objects.
106.4 Testing
● For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly elaborated
the concept of aggregation and composition in terms of ownership and life cycle.
107. Evaluation Task (Unseen) [Expected Time = 40 mins for all tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
139
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
109.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
109.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
140
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
141
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
1432.
Activity Time
Boxing 1443.
Objective of the
Experiment 1444.
Concept
Map 1445.
Homework before
Lab 1455.1
Practices from
Home 1456.
Procedure &
Tools 1456.1
Tools
1456.2
Setting-up Visual Studio 2008
1456.3
Walkthrough Task
1457.
Practice
Tasks 1467.1
Practice Task 1
1477.2
Practice Task 2
1477.3
Practice Task 3
1477.4
Outcomes
1477.5
Testing
1478.
Evaluation Task (Unseen)
1489.
Evaluation
Criteria14810. Further
Reading 14810.1
Books
14810.2
Slides
149
142
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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++
143
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
informs the compiler that programmer is going to define a function or class template. Further, the variable
with reserved word class or typename within angle brackets (< >) is known as the template argument. This
template argument is replaced with specific data type with each function call statement.
Relevant Lecture Readings:
● Lectures: 29, 30, 31
● Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 682- 703
The statement of template definition in C++ code by itself is not able to generate any code. Code generation
for a specific template function takes place at the time of function invocation. This is due to the fact that
upon function invocation compiler comes to know about the type to substitute template parameter. This is
known as instantiating the function template.
144
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Concerning class templates in C++, it is important to point out here that C++ provides a powerful and
versatile collection of functions and classes for common data structures i.e. vector, stack, queue etc. This
collection of classes is known as Standard Template Library (STL). Functions and classes in STL provides
well-organized and extensible framework to develop certain applications.
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.
In the source file, which is created in the project “TemplateExample” write following C++ code:
145
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and
warnings that are present in your code.
146
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● A single data member as an array named list of size 10 to store certain elements
● A constructor to initialize queue with value 0 or 0.0 at all its indexes
● Three member functions i.e. sort() to sort the elements of the queue, max() that returns the
maximum value present in the queue, min() that returns the smallest value present in the queue,
and return_queue() that returns all the elements of the queue (in case of there being multiple
maximum and minimum values present in the queue, the member functions should return notify
the user of the number of times that value has been repeated in the queue and then return that value
to the main function).
In the main() function, create three objects with different data types of class queue and test the functionality
of member functions for various values of data members for these objects.
116.4 Outcomes
After completing this lab, student will be able to understand the use and working of function and class
templates in C++.
116.5 Testing
● Test cases for Practice Lab 1
147
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
● For Practice Lab 3, lab instructor should check the creation of three instances of List class while
each having an array of different data type. Moreover, check the required functionality of member
functions with these instances.
Table 3: Practice Tasks Confirmation
117. Evaluation Task (Unseen) [Expected Time = 45 mins for all tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
119.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
148
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
119.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
149
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
150
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction 1522. Activity Time Boxing 1563. Objective of the
Experiment 1574. Concept Map 1575. Homework before Lab 1585.1
Practices from home 1586. Procedure & Tools 1596.1 Tools
1596.2 Setting-up Visual Studio 2008 1596.3 Walkthrough Task
1596.3.1 Writing Code 1597. Practice Tasks 1617.1 Practice Task 1
161 1617.2 Practice Task 2 161 1617.3 Outcomes 1617.4
Testing 1618. Evaluation Task (Unseen) 1619. Evaluation
Criteria 16110. Further Reading16210.1 Books 16210.2 Slides 162
151
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the above figure, consider Object1, Object2 and Object3 are three of a class. Each object has its own
private data members. The class has a static data member that is share among all the object of that class.
This data member has it own memory allocated that is separate from the memory allocated for each object
of that class.
Static keyword can be used as:
1. Variables in functions
Static variables when used inside function are initialized only once. They hold their value even through
function calls
152
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
2. Class objects
Objects declared static are allocated storage in static storage area. They have a scope till the end of program
153
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Static objects are also initialized using constructors like other normal objects.
154
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
for static data member is made, user cannot redefine it. Though, arithmetic operations can be
performed on it.
155
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
156
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
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.
157
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
158
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Create a SavingsAccount class. Use a static data member annualInterestRate to store the annual
interest rate for each of the savers. Each member of the class contains a private data member savingsBalance
indicating the amount the saver currently has on deposit. Provide member function
calculateMonthlyInterest that calculates the monthly interest by multiplying the balance by
annualInterestRate divided by 12; this interest should be added to savingsBalance. Provide a static
member function modifyInterestRate that sets the static annualInterestRate to a new value.
Write a driver program to test class SavingsAccount. Instantiate two different objects of class
SavingsAccount, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set the
annualInterestRate to 3 percent. Then calculate the monthly interest and print the new balances for each of
the savers. Then set the annualInterestRate to 4 percent, calculate the next month's interest and print the
new balances for each of the savers.
159
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the source file, which is created in the project “StaticExample” write following C++ code:
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.
160
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
o Create a Calculator class that has following methods: sum, multiply, divide, modulus , sin , cos , tan
The user should be able to call these methods without creating an object of Calculator class.
o Create a class employee with data members as name, emp_id, salary and a static variable count.
Count should count total number of objects created for employee. In main() invoke setters and
getters to take input in attributes of employee.
126.3 Outcomes
After completing this lab, student will be able to implement the concepts static keyword.
126.4 Testing
● For Practice Task 1, Lab instructor must verify the implementation and required relationships
among all classes and objects. In addition, it is required to confirm that code has clearly elaborated
the concept of aggregation and composition in terms of ownership and life cycle.
Table 3: Practice Tasks Confirmation
127. Evaluation Task (Unseen) [Expected Time = 55 mins for all tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
161
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
4 Comments 5
5 Good Programming 10
Practices
Total Marks 100
129.1 Books
● Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition
129.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
162
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
163
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
1662.
Activity Time
boxing 1663.
Objective of the
Experiment 1664.
Concept
Map 1674.1
Friend
Functions 1674.2
Friend
Classes 1675.
Home Work Before
Lab 1685.1
Practices from
Home 1686.
Procedure &
Tools 1686.1
Tools
1686.2
Setting-up Visual Studio 2017
1686.3
Walkthrough Task
1686.3.1
Writing
Code 1686.3.2
Compilation
1706.3.3
Executing the
Program. 1707.
Practice
Tasks 1707.1
Practice Task 1
1707.2
Practice Task 2
1707.3
Practice Task 3
1717.4
Outcomes
1717.5
Testing
1718.
Evaluation Task (Unseen)
164
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
1729.
Evaluation
Criteria 17210.
Further
Reading 17210.1
Books
17210.2
Slides
172
165
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
166
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
class second
{
In private:
the syntax above it must be understood that access specifiers are not applicable on friend functions i.e. whether you
int inmem1;
write the function public or private it has no effect. Another important thing to always remember is that it is
compulsory toint writemem2;
the keyword friend with the function prototype but writing the friend keyword in the function
public:
definition will result in a syntax error. In the above code the friend function is bridge between two classes using a
singlefriend
function.void display(
Creating first,
this environment second
is purely the ); //Friend
programmers choice. function
It is not prototype
necessary that you have a
}; working like a bridge. You can always have a single friend function inside a single class.
function
When discussing friend functions one must remember that friend functions are never part of a class. They are written
in void
the classdisplay(
to show thatfirst o1,
they have secondwith
a friendship o2) //Note
the class. Friend that
functions friend
are not is not
called using the dotwritten
notation or
by{using the scope resolution. Friend functions are called like a conventional function. Now when using the friend
cout<<o1.member1<<o1.membern;
function we can access both public and private data members directly as if there is no such thing as an access specifier.
Ancout<<o2.mem1<<o2.mem2;
important note regarding friend functions is that these functions should not be used to relax the access specifiers.
}
Secondly the friendship of a function is one sided i.e. the function can access the class members but the class cannot
voiddeceleration
access main( ) that are made inside the function.
{
firstFriend
133.2 obj1;Classes
second obj2;
A display(
friend function has access to those classes
obj1,obj2); with which
//Simple it is friend.
calling. Sometimes
Cannot a situation
use the arises when we
dot operator
} to make two classes friends with each other. This means that a class can access the public and private
want
members of another class directly. To achieve this you must right the friend class statement in the
befriending class.
class first
{
private:
friend class second; //Declaration of friend class 167
int member1;
int membern;
public:
first()
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
void main( )
{
first obj1;
second obj2;
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.
168
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
169
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Figure 1: The series class and the sum friend class. The display function is a friend function.
135.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.
170
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
The data class will be composed of two floating point data members namely a and b. The class will also be
composed of a friend function display that can display all the data members.
The calculation class is responsible for performing operations on the data class and hence it has three
functions as follows:
● A function to compute the Square of sums i.e. (𝑎 + 𝑏)2 = 𝑎2 + 𝑏 2 + 2𝑎𝑏
● A function to compute the Square of difference i.e. (𝑎 − 𝑏)2 = 𝑎2 + 𝑏 2 − 2𝑎𝑏
136.4 Outcomes
After completing this lab, students will be able explain the difference between a member function and a
friend function. The students will be able to create friend functions and friend classes. Further they will be
comfortable with the manipulation of objects using both friend functions and classes.
136.5 Testing
a =1; proot= 1
b =2; nroot = -3
c =-3
171
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
139.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
139.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
172
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
173
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
174
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Table of Contents
1. Introduction
1772.
Activity Time
boxing 1773.
Objective of the
Experiment 1774.
Concept
Map 1784.1
Introduction to Operator
Overloading 1784.2
Which Operators Can Be
Overloaded 1784.3
Operator Overloading – General
Rules 1784.4
Operator Overloading –
Syntax 1784.5
Stream Insertion and Extraction
Operators 1794.6
The Assignment Operator and the Copy
Constructor 1795.
Home Work Before
Lab 1815.1
Practices from
Home 1816.
Procedure &
Tools 1816.1
Tools
1816.2
Setting-up Visual Studio 2008
1816.3
Walkthrough Task
1816.3.1
Writing
Code 1816.3.2
Compilation
1836.3.3
Executing the
Program 1837.
Practice
Tasks 1847.1
Practice Task 1
1847.2
Practice Task 2
175
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
1847.3
Practice Task 3
1857.4
Outcomes
1857.5
Testing
1858.
Evaluation Task (Unseen)
1869.
Evaluation
Criteria 18610.
Further
Reading 18710.1
Books
18710.2
Slides
187
176
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
177
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
178
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
is a binary operator that requires one calling object and one object being passed as an argument. The return
type of this function is dependent on what you wish to return. If you are computing an expression having
more than two objects then you will need to create a temporary object and return the object for further
computing of the expression. Refer to the walkthrough task in this lab.
int operator + (classname obj) //The plus operator
{
. . .
}
Similarly the code snippet below shows the pre increment operator being overloaded.
int operator ++ ( ) //The pre increment operator
{
. . .}
Similarly the code snippet below shows the post increment operator being overloaded. The parameter is in
fact never passed; it is just an indicator to show that this function is a post increment operator. Hence
whenever there is an operator with a unary operator then it indicates that you are referring to a post
increment operator.
int operator ++ (int n) //The post increment operator
{
. . . }
class DoB
{
private:
int month, day, year;
public:
DoB( )
{
cout <<“Nullary constructor";
o month = day = year = 0;
}
~DoB ( )
{
cout << ”Destructor called";
} ~DoB ( )
friend ostream
{ & operator << ( ostream & os, DoB &d );
friend istream & operator >> ( istream & is, DoB &d );
}; cout << ”Destructor called";
179
}
ostream
friend & operator <<&( operator
ostream ostream & os,
<<DoB( &dostream
) & os, DoB &d );
{
friendosistream & "."
<< d.day << operator >><< ("."istream
<< d.month << d.year;& is, DoB &d );
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
180
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
On the other hand the assignment operator is used after an object is created. As the name says the assignment
operator will assign values to an object that has already been created.
Your compiler is aware of this difference and hence you cannot call the copy constructor when the
assignment operator is need. The vice versa of this is also true.
● Overload the stream insertion and extraction to input and output data of the objects
● Use the + operator to find the total tax collected in a day.
● Create the ++ operator to fine a particular car.
181
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
In the source file created in the project “tolltax” write the following C++ code:
182
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
Figure 1: The “toll” class demonstrating the use of various overloaded operators
145.3.2 Compilation
▪ After writing the code, compile your code according to the guidelines mentioned. Remove
any errors and warnings that are present in your code.
183
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
184
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
operator
● Overload the + operator so that it works with a fraction class object.
● Overload the – operator so that it works with a fraction class object.
● Overload the * operator so that it works with a fraction class object.
In the end create a display function through which you can display your fractions.
146.4 Outcomes
After completing this lab, students will be able to customize an operator so that it works with their classes.
Students will be able to redefine familiar mathematical operators and also the stream insertion and
extraction operators.
146.5 Testing
Test Cases for Practice Task-1
obj2.numerator = 3 −2
Difference = obj1- obj2 =
obj2.denominator = 2 2
3
Product = obj1*obj2 =
4
185
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
186
Capital University of Science and Technology Islamabad
Department of Computer Science/ Software Engineering,
Faculty of Computing
149.1 Books
● Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell
149.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\
187