Академический Документы
Профессиональный Документы
Культура Документы
Islamabad
LAB MANUAL
OBJECT ORIENTED PROGRAMMING
First Edition
ii
Lab Designers
Dr. Muhammad Azhar Iqbal
Assistant Professor
Department of Computer Science
iii
Table of Contents
Preface
iv
13
22
32
41
52
61
72
80
89
98
106
115
124
131
139
140
iv
Preface
earning is a process that requires class instructions and practice labs. If we omit any of
the above then the learning process is clearly flawed. This book is an attempt to
standardize the lab instructions through the development of a lab curriculum that is based on
the class curriculum. This document is intended to be used by lab instructors, course
instructors and students.
The intent of this curriculum is to define a clear lab structure that can be followed by
the lab instructor and the students. In the absence of such curriculum the labs are often run
without any formal structure. Another problem is that there is no grading criteria defined for
each lab which leads to unethical practices. Perhaps one of the greatest problems faced by lab
instructors is that they are unable to keep the students occupied for the entire duration of the
lab due to which the learning process is greatly hampered.
The labs have been developed in a way that there is synchronization between the class
and the lab. The entire book has been divided into 15 labs having duration of 3 hours each.
Students of the course are expected to carefully read the concept map before coming to the
lab. Students come to the lab with a designs/ program that will be handed over to the lab
instructor for further grading. This code/ design is primarily based on previous learnings and
experiments. Each lab has a detailed walkthrough task which provides a problem statement
and its programmable solution to the students. The students can raise queries about the code
provided and the lab instructor will guide the students on how the solution has been designed.
Thereafter predefined practice questions have been presented such that each question has a
fix duration and grade. Students are graded upon their accomplishments in these practice
tasks. At the end of the lab the lab instructor will assign an unseen task to the students. This
unseen task contains all the concepts taught in the lab. These unseen tasks have a higher level
of complexity and generally have a greater gain in terms of marks.
What sets these labs apart is the fact that a clear grading criteria has been defined for
each lab. Students are aware of the grading criteria and are expected to meet the requirements
for successful completion of each lab.
Page 1
Table of Contents
1.
Introduction
2.
3.
4.
Concept Map
4.1
4.2
4.3
4.4
4.5
4.6
4
4
4
5
6
6
5.
6.
7.
5.1
5.2
7
8
6.1
6.2
6.3
8
8
8
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
10
7.1
7.2
7.3
7.4
7.5
7.6
10
10
10
10
10
11
Practice Task 1
Practice Task 2
Practice Task 3
Practice Task 4
Outcomes
Testing
8.
11
9.
Evaluation criteria
11
10.
Further Reading
12
10.1
10.2
12
12
Books
Slides
Page 2
Lectures: 1, 2
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Chapters: 5, 10
Activity Name
Evaluation of Design
Setting-up Visual Studio
Walkthrough Task
Practice tasks
Evaluation Task
Total Time
15 mins
5 mins
25 mins
85 mins
50 mins
170 Minutes
Page 3
4. Concept Map
4.1 Reusability/ Modularity of Code
Computer programmers have always devised mechanisms through which they can make their code more
understandable and then reusable. In this regard functions offer a very popular and easy mechanism of introducing
the above goals. Function handling operates on the concept of provision of service/ functionality. We can call the
services of a function by providing the required data and in result getting the promised service from the function.
Reusability of code means devising methods through which you can use code again and again without having to
copy-paste in the source file. Modularity of code means dividing the code into small, manageable and easy to
understand segments.
4.2 Function Prototype and Function Definition
The creation of a function is based on two similar yet distinct statements called a function definition and function
prototype.
A function prototype explains only how a function will be called and what data type it will return. A function
definition on the other hand matches the function prototype and also includes a function body.
For example the following is the function prototype of a function that finds the sum of two integers passed to it:
void addtwo (int, int);
The following is the function definition of the above defined function:
void addtwo (int a, int b)
{
int c=a+b;
cout<<The sum is <<c;
}
4.3 Function Arguments and Parameters
There are two types of variables a function is related with; namely function arguments and function parameters.
Function arguments are those variables that are provided to a function. These variables are passed whenever a
function is called.
Function parameters are those variables that are created and initialized when parameters are passed to a function.
The scope of a function parameter is always within the body of the function. It should be pointed out here that any
variable that is created in a function body has a local scope and cannot be accessed outside the function body.
The data type of arguments must match the parameters of a function.
In the following example, variables a and b are parameters of the function addtwo( ).
void addtwo (int a, int b);
{
Department of Computer Science,
MAJU
Page 4
Page 5
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.
Page 6
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.
Page 7
lab instructor.
Page 8
Page 9
7.6 Testing
Test Cases for Practice Task-1
Sample Inputs
Number: 3
Sample Outputs
5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25,
Sample Outputs
Result = 4194304
Check that the function works with pass by reference
Sample Outputs
Sum = 20
Check that pointers have been used to iterate the array
Sample Outputs
Invalid Input
Number: 5.5
Invalid Input
Number: 5
120
Confirmation
Comments
Page 11
Task No
Description
Marks
4.1
6
7.1
7.2
7.3
7.4
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Practice task 2 with Testing
Practice task 3 with Testing
Practice task 4 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
20
5
10
10
10
15
20
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 12
Page 13
Table of Contents
1.
Introduction
15
2.
15
3.
15
4.
Concept Map
16
4.1
4.2
4.3
4.4
4.5
4.6
16
16
16
17
17
17
5.
6.
7.
Object
Data Members
Member Functions
Constant Member Functions
Class
Encapsulation
18
5.1
5.2
18
18
18
6.1
6.2
6.3
18
18
18
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
20
7.1
7.2
7.3
7.4
7.5
20
20
20
20
20
Practice Task 1
Practice Task 2
Practice Task 3
Outcomes
Testing
8.
21
9.
Evaluation Criteria
21
10.
Further Reading
21
10.1
10.2
21
21
Books
Slides
Page 14
Lectures: 3, 4
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 195-201
Total Time
15 mins
5 mins
25 mins
80 mins
45 mins
170 Minutes
Page 15
4. Concept Map
4.1 Object
In OOP an object is a very much like a real world object. An object can be defined as a collection of state and
behaviour. For example, consider the example of a cat. A cat is has both a state and behaviour. The state of a cat is
its attributes namely colour, breed, gender, age, weight, height, etc. Whereas the behaviour of a cat is its sound,
eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique characteristics and
behaviours.
In programming an object is a collection of variables and functions that together have a unique purpose of
identifying a distinctive entity.
4.2 Data Members
Again referring to the concept of an object and the example of a cat. The cat had a number of characteristics or
attributes that can be used to identify a cat. In programming these attributes can be programmed by using regular
variables that are called data members. A class can be composed of a number of data members of various types. The
data members of a class are private by default i.e. they are not directly accessible outside the class.
Here it is important to point out that often people casually refer to these as variables, which is a wrong terminology.
These should only be called data members or class variables.
4.3 Member Functions
Again referring to the concept of an object and the example of a cat. The cat had a number of behaviours or things
that a cat does. In programming these behaviours can be programmed by using functions that are called member
functions. A class can be composed of a number of member functions of various types. Overloading of member
functions is also permitted in C++. The implementation section of member functions can be separated whereby the
body of the function is created outside the class but the function prototype has to exist in the body of the class. The
implementation section is separated by writing the return type followed by class name. This is further followed by
scope resolution operator :: and then the remaining function definition.
using namespace std;
class myclass
{
int datamember;
int memberfun(int);
// Function prototype
};
int myclass :: memberfun (int x)
// Note the scope resolution operator
{
...
// Function body
}
void main( )
{
}
Page 16
{
cout<<The sum is= <<s;
}
4.5 Class
A class is a collection of data members and member functions. A class is used to define an abstract data type. This
abstract data type is used in the construction of an object which is used to access all the data members and member
functions. A class has to be created before it can be used. Provided below are the syntax for creating a class.
using namespace std;
class myclass
{
int datamember;
};
void main( )
{
void main( )
{
}
}
class myclass
{
int datamember;
void memberfun (int)
{
...
}
};
//Semicolon is necessary
4.6 Encapsulation
Encapsulation is a very important design goal because of which OOP is preferred over conventional programming.
Encapsulation is a quality because of which data and function are stored in a single unit commonly known as a class.
This unit/ bundle ensures that the data is not openly accessible to the outer world. The access is provided by the
functions that are part of the unit/bundle. This means that the functions work like doors in a room. You can prevent
thieves from breaking in. Only those people can enter who come through the door.
Page 17
Page 18
Figure 1: Class for creating a cylinder with its relevant data members
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.
Page 19
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:
\\dataserver\assignments$\OOP\Lab02
7.1 Practice Task 1
[Expected time = 25 mins]
Write a C++ program that creates a class called laptop. The data members of the class are brand (string), model
(string), serial (int), colour (string), price (float), processor speed (float), RAM (int), screen size(float).
Create member function that will set the individual values. Since the RAM can be upgraded therefore create a
function that allows you to upgrade the RAM only. In the end, create a function that will display all the data
members.
7.2 Practice Task 2
[Expected time = 25 mins]
Write a class called rectangle. Your task is to store the length and width of the rectangle. Write a member function
called increment that will add 1 to the value of length and width. Also write a function that will compute the area of
the rectangle. Finally write a constant function that will display the length, width and area of the rectangle.
Demonstrate the use of the object in the main function. Make sure that the function names are meaningful and self
descriptive.
7.3 Practice Task 3
[Expected time = 30 mins]
Write a program that creates a class called number. Your class will have two data members namely num (float) and
result (int). To find the factorial of the entered number you will need to design three functions as follows:
Function to determine if a number is a whole number or not
Function to determine if the number is positive or not
Function to find the actual factorial
Function to display the number and its factorial
Remember that to find the factorial the number must of positive and a whole number. So if any of these conditions
are not met then you cannot determine the factorial.
7.4 Outcomes
After completing this lab, students will be able to design a basic class with data members and member functions.
7.5 Testing
Test Cases for Practice Task-1
Sample Inputs
Set the following values
Brand = DELL
Model = 1565D
Serial = 123456
Colour = Silver
Price = 64500.5
Processor = 2.8
RAM = 2
Screen = 15.6
Sample Outputs
Brand = DELL
Model = 1565D
Serial = 123456
Colour = Silver
Price = 64500.5
Processor = 2.8
RAM = 3
Screen = 15.6
Sample Outputs
Length = 5
Width = 11
Area = 55
Department of Computer Science,
MAJU
Page 20
Sample Outputs
Invalid Input
Number: 5.5
Invalid Input
Number: 5
Number = 5
Factorial = 120
Table 2: Confirmation of practice tasks T1, T2 and T3
Practice Tasks
T1
T2
T3
Confirmation
Comments
Task No
Description
Marks
4.1
6
7.1
7.2
7.3
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Practice task 2 with Testing
Practice task 3 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
20
5
10
10
10
15
10
80
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 21
Page 22
Table of Contents
1.
Introduction
24
2.
24
3.
24
4.
Concept Map
25
4.1
4.2
4.3
5.
6.
7.
25
25
26
27
5.1
27
27
6.1
6.2
6.3
27
27
27
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
29
7.1
7.2
7.3
29
30
30
Practice Task 1
Outcomes
Testing
8.
30
9.
Evaluation Criteria
31
10.
Further Reading
31
10.1
10.2
31
31
Books
Slides
Page 23
Lectures: 3, 4, 5, 6
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 201-212
Activity Name
Evaluation of Design
Setting-up Visual Studio
Walkthrough Tasks
Practice tasks
Evaluation Task
Total Time
20 mins
5 mins
40 mins
60 mins
45 mins
170 Minutes
Page 24
4. Concept Map
4.1 Access Specifiers Public and Private Access
Access specifier also known as access modifier provides a technique for enforcing access control to class members
(data members and member functions). The use of access specifiers enforces encapsulation and data hiding. C++
provides three access specifiers i.e. public, private and protected. In this lab we will only cover the public and the
private access specifier. The protected specifier is left for future discussions.
The public access specifier is the one that provides unrestricted access to the class members. While the private
access specifier provides a very strict/ restricted access to class members. All the class members that are written
under the public access can be accessed both inside and outside the class without any restriction. On the other hand
all the class members written as private are accessible inside the class but are not accessible outside the class. The
best and most common way of accessing private data members is through the use of a public functions.
When we are discussing access specifiers it must be pointed out that by default classes are private whereas
structures are public. Hence if you do not write private then your listed class members are considered private in a
class.
The correct convention for the use of access specifiers is that data members are kept private whereas functions are
kept public. Hence you are providing a public interface for accessing restricted items in a class.
4.2 Constructors
A constructor is a function that is automatically called when an object is created. This function can exhibit the
regular behaviour of any function except that it cannot return a value. The reason why constructors are needed is that
unlike regular functions which need to deliberately called, a constructor will be automatically called when an object
is created. Every constructor has a body from where we can call regular member functions.
Department of Computer Science,
MAJU
Page 25
A very important question which is often asked is that how does the compiler know that the constructor function
needs to be called automatically? The answer is very simple. A constructor is a function that has the same name as
the class. Whenever an object is created the compiler searches for a function having the same name as the class i.e.
the constructor. Given below is a sample code that shows the class constructor. Generally the constructor is defined
as public. Also the constructor can be overloaded like a regular member function. An important point regarding a
constructor is that it cannot return a value. In fact writing the keyword void is strictly prohibited.
using namespace std;
class myclass
{
private:
int datamember;
//Private data member
public:
myclass( );
//Class constructor
{
cout<<Hello you have called the class constructor;
}
};
void main( )
{
myclass obj;
}
4.3 Destructors
Constructors are designed to help initialize/ create an object. Destructors on the other hand do exactly the opposite.
Destructors are called whenever an object goes out of scope. When this happens it is necessary to perform cleanup
procedures especially when you have used dynamic memory or you have been working with pointers in your code.
The destructor function can be used to free up memory that you have allocated or dereference pointers that were
referenced. The rules for a destructor are as follows:
They have the same name as the class just simply preceded by a tilde (~)
They can take no arguments
They cannot return anything, not even void.
using namespace std;
class myclass
{
private:
int datamember;
//Private data member
public:
myclass( );
//Class constructor
{
cout<<Hello you have called the class constructor;
}
~myclass( );
//Class constructor
{
cout<<Hello you have called the class destructor;
}
};
Page 26
Page 27
Page 28
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.
LeCream allows its customers to purchase a vanilla wafer with their ice cream. If the customer wants to
purchase the wafer he will have to pay an additional Rs 10. This amount should be added to the total
amount payable by the user.
If the customer asks for chocolate flavour then he will have to pay an additional amount i.e. Rs 120 for two
scoops and Rs 180 for three scopes. Design a function that will be called if the customer chooses flavoured
ice cream.
The program should show a menu that asks the customer for his requirements and then displays the final
payable amount with full details about the flavour, number of scoops and wafer
Department of Computer Science,
MAJU
Page 29
In the end create a class destructor that displays a thank you message to the user.
Design your program using sound OOP practices. Carefully determine the data members, member functions, access
specifiers, activities to be performed in the constructor. Make sure that you use good naming conventions in your
code. A good design can earn you higher marks.
7.2 Outcomes
After completing this lab, students will be able to design a class that correctly implements class members by
observing access specifiers. The students will also be familiar with the use of a constructor and destructor.
7.3 Testing
Test Cases for Practice Task-1
Sample Inputs
Flavour = chocolate
Wafer required = yes
Number of scoops = 3
Sample Outputs
Your choice of ice cream is as follows
Flavour = chocolate
Number of scoops = 3
Wafer is required
Total price is 190
Thank you for visiting LeCream!
Flavour = Coffee
Wafer required = yes
Number of scoops = 3
Flavour = Mango
Wafer required = No
Number of scoops = 4
Invalid Input
Thank you for visiting LeCream!
Confirmation
Comments
Page 30
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned
marks which will be evaluated by the instructor in the lab depending on the accomplishment of the assigned tasks.
Table 3: Evaluation of the Lab
Sr.
No.
1
2
3
4
5
Task No
Description
Marks
4.1
6
7.1
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
10
5
50
15
10
90
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 31
Page 32
Table of Contents
1.
Introduction
34
2.
34
3.
34
4.
Concept Map
34
4.1
4.2
4.3
34
35
35
5.
6.
7.
Function Overloading
Constructor Overloading Parameterized and Nullary Constructors
Copy Constructors
36
5.1
36
36
6.1
6.2
6.3
36
36
36
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
38
7.1
7.2
7.3
7.4
38
39
39
39
Practice Task 1
Practice Task 2
Outcomes
Testing
8.
39
9.
Evaluation Criteria
40
10.
Further Reading
40
10.1
10.2
40
40
Books
Slides
Page 33
Lectures: 6, 7, 8
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 212-213, 216-217
Activity Name
Evaluation of Design
Setting-up Visual Studio
Walkthrough Tasks
Practice tasks
Evaluation Task
Total Time
25 mins
5 mins
35 mins
50 mins
55 mins
170 Minutes
4. Concept Map
4.1 Function Overloading
Function overloading is an advanced concept in modern languages where two function can have the same name. The
question that arises here is that how does a compiler know which function to call. The simple answer is that the
function calling is determined based on the type of parameters/ the number of parameters being passed/ order of
parameters being passed. Hence two function can have the same name but there must be a difference in the number
of parameters, type of parameters or the order of parameters. For example in the function prototypes below the
function fun( ) has been overloaded and its different flavours are presented.
int fun (int, float, float);
int fun (int, float);
Department of Computer Science,
MAJU
Page 34
//Nullary constructor
//Overloaded Constructor:
Page 35
example objects that do not use pointers or arrays. Although the default copy constructor will copy any type of
object but it is strongly recommended that the copy constructor be used only for objects that have non pointer data
members. The default copy constructor performs a member by member copy i.e. the copy constructor creates an
exact copy where data members are copied one by one to the new object. Always remember that in copy
constructors the original object is maintained in its original state and the copy changes are only exhibited in the
newly created object. In this lab we will just restrict ourself to the use of the default copy constructor.
The default copy constructor can be explicitly called as follows:
clss obj2(obj1);
Both statements create an object of the clss class. Of course any of the above statements can be used for copying an
object into another object.
Caution: The copy constructor is always called at the time of creating a new object. If at any time after the creation
of objects you copy contents of one object to the other then the copy constructor is not called. We will discuss more
on this in future lectures.
Page 36
class student
{
private:
string name;
int age;
public:
student()
//Nullary constructor
{
cout<<"Enter name ";
cin>>name;
cout<<"\nEnter age ";
cin>>age;
}
student(string n, int a)
//parameterized Constructor
{
name=n;
age=a;
}
void showall()
{
cout<<"\nName= "<<name;
cout<<"\nAge= "<<age;
}
};
int main()
{
student s1;
//Creation through nullary constructor
student s2("Ali", 30); //Creation through parameterized constructor
s1.showall();
s2.showall();
student s3(s1);
//Calling copy constructor for s3
s3.showall();
return 0;
}
Figure 1: The student class demonstrating the use of a parameterized and nullary constructor. Also note the default
copy constructor being used
Page 37
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.
Sample Outputs
Your LCD purchase details are:
Length = 48
Width=30
Length = 48
Width = 30
Price=93600
Using parameterized constructor (integer)
Length = 48
Width = 30
Length = 40.5
Width = 30.5
Price=80291.25
Sample Outputs
Call the display function using the new object;
The new object will contain the values of the previous object.
Confirmation
Comments
Page 39
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned
marks which will be evaluated by the instructor in the lab depending on the accomplishment of the assigned tasks.
Table 3: Evaluation of the Lab
Sr.
No.
1
2
3
4
5
6
Task No
Description
Marks
4.1
6
7.1
7.2
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Practice task 2 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
10
5
30
20
25
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 40
Page 41
Table of Contents
1.
Introduction
43
2.
43
3.
43
4.
Concept Map
43
4.1
4.2
4.3
4.4
43
44
45
46
5.
6.
7.
47
5.1
47
48
6.1
6.2
6.3
48
48
48
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
49
7.1
7.2
7.3
7.4
49
49
50
50
Practice Task 1
Practice Task 2
Outcomes
Testing
8.
50
9.
Evaluation Criteria
50
10.
Further Reading
51
10.1
10.2
51
51
Books
Slides
Page 42
Lectures: 8, 9, 10
Activity Name
Evaluation of Design
Setting-up Visual Studio
Walkthrough Tasks
Practice tasks
Evaluation Task
Total Time
25 mins
5 mins
30 mins
65 mins
45 mins
170 Minutes
4. Concept Map
4.1 Creating a customized copy constructor
Although C++ provides you with a basic copy constructor, but still there are occasions when you need to design you
own copy constructor. Given below are some of the reasons why you might want to create a copy constructor.
You need to copy only some of the data members to a new object.
Your objects contain pointers.
Your objects contain dynamic data members.
Department of Computer Science,
MAJU
Page 43
There may be other numerous reasons why you might want to create a customized copy constructor. Before you
begin you must familiarize yourself with the syntax of a copy constructor. A copy constructor always receives an
object as a parameter and hence we can extract the data from the parameterized object and place the data in the
newly created object. Presented below are the two syntax for copy constructors:
MyClass (MyClass& other );
// A copy constructor
called MyClass
prototype
for
class
prototype
for
In the above prototypes the object which will be copied is called other. By writing the const keyword a copy of an
object can be created without any change to the inherent data members. Although only some of the data members
can be copied.
4.2 Shallow Copy Constructor
A shallow copy constructor is a copying function that does a member by member copy of one object to another. The
copy constructor provided by default is a shallow copy constructor. If a class does not have any dynamic members
then only a shallow copy constructor is needed.
Consider another case in which you want to create a partial copy of an object i.e. you only want to copy some of the
static data members then we need the help of a shallow copy constructor.
class example
{
private:
int a;
int b;
public:
example (example & parame)
{
a=parame.a;
b=parame.b;
}
void showall( )
{
cout<<"\na="<<a;
cout<<"\nb="<<b;
}
example( )
{
a=10;
b=20;
}
};
int main()
{
example obj1;
example obj2(obj1);
obj1.showall();
obj2.showall();
return 0;
}
//Simple constructor
Page 44
In the above code when object obj1 is created the nullary constructor is called and hence values 10 and 20 are
allocated to data members a and b respectively. Now when object obj2 is being created obj1 is passed to the copy
constructor as an argument. While creation of obj2 control is never shifted to the basic constructor because we are
attempting to make a new object by copying.
4.3 Deep Copy Constructor
A deep copy constructor is a constructor that has been designed to handle pointers and dynamic data members.
Although a shallow copy constructor will also copy pointers but it does so in an incorrect way. Hence it is logically
wrong to use a shallow copy constructor for dynamic data members.
The problem with shallow copy constructors:
The problem with shallow copy constructors is that suppose you have a class that has a pointer as a data member and
you want to create a copy of this class object. When you call the shallow copy constructor it will copy the pointer
data member to the new object. You might think this is what we want but in fact it is wrong because copying a
pointer means that you have copied the data and the address to which the pointer is pointing. Hence you have on
hand two objects that are pointing to the same memory location. Always remember that two objects should have
their own distinct identity and distinct memory.
Memory
Copy of
Object 1
Object 1
(a)
Memory
Copy of
Object 1
Object 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.
class example
{
private:
char *str;
int
len;
public:
example( );
example(char *s);
example(const example &st)
{
len = st.len;
str = new char [len + 1];
strcpy(str, st.str);
}
// other stuff
};
Page 45
When working with copy constructors it is important to remember that the copy constructor function prototype is the
same for both shallow copy and deep copy. Hence the difference lies in the fact that dynamic data members are
being handled or not. To determine if a deep copy or shallow copy constructor is being used you have to study the
copy constructor body.
4.4 Working with Arrays
As explained earlier, arrays are of very importance in every program. The main reason for their importance is that
they provide contiguous memory locations that can be accessed with a simple iterative mechanism like loops. When
it comes to classes we have many options relating to arrays. All the possibilities related to arrays are part of this lab.
Given below is a class named example that contains a simple (static) floating point array a. This array can be
initialized with a constructor or with a simple member function as follows.
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;
public:
example()
{
a=new float[10];
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
Department of Computer Science,
MAJU
Page 46
therefore the size of the array can be provided at run time. In this particular code since the size is not passed there
may be a possibility that the programmer crosses the array boundary.
Another option which is very popular among programmers is that the size of the array can be stored as a data
member.
class example
{
private:
float *a;
public:
example(int size)
{
a=new float[size];
to the constructor
for(int i=0; i<=9;i++)
{
a[i]=0;
}
}
void showall (example arr[ ], int size)
//Size is passed to restrict from crossing array boundary
{
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
cout<<arr[i].a[j];
}
}
}
};
int main()
{
const int size=10;
example obj1[size]=example(size);
//array of objects initialized with parameterized constructor
example obj2;
obj2.showall( obj1, size );
return 0;
}
Page 47
Page 48
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.
Page 49
Sample Outputs
After selective copying only the permanent attributes contain
values.
Colour = Hot Red
Owner =
Year of manufacture =
Seats = 2
Cubic Capacity = 5700
Engine number =
Frame number =
Sample Outputs
Upon calling the display function of object one the modified
values will be displayed
Upon calling the display function of object two the same
modified values will be shown.
Confirmation
Comments
Page 50
Task No
Description
Marks
4.1
6
7.1
7.2
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Practice task 2 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
10
5
30
20
25
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 51
Page 52
Table of Contents
1.
Introduction
54
2.
54
3.
54
4.
Concept Map
54
4.1
4.2
Friend Functions
Friend Classes
54
56
56
5.1
56
5.
6.
7.
57
6.1
6.2
6.3
57
57
57
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
58
7.1
7.2
7.3
7.4
7.5
58
59
59
59
59
Practice Task 1
Practice Task 2
Practice Task 3
Outcomes
Testing
8.
60
9.
Evaluation Criteria
60
10.
Further Reading
60
10.1
10.2
60
60
Books
Slides
Page 53
Lecture: 11 - 12
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 468-475
Activity Name
Evaluation of Design
Setting-up Visual Studio
Walkthrough Tasks
Practice tasks
Evaluation Task
Total Time
25 mins
5 mins
25 mins
80 mins
35 mins
170 Minutes
4. Concept Map
4.1 Friend Functions
Before going to the syntax of friend functions it is important that we highlight why they are needed. Friend functions
provide a relaxing mechanism through which we can access the private data members of a class directly without any
question being asked. This does not mean that we have relaxed the access specifiers. A friend function provides
access to the private and public data members of a class from only within its body. Friend functions are needed
because sometimes if we have multiple classes and we want to manipulate the class members through a single
function.
Department of Computer Science,
MAJU
Page 54
Another similar scenario is when we want a regular function (that is not member of a class) to access private
members of a class. The final scenario is the use of friend functions in operator overloading (will be discussed in lab
7).
Always remember that friend functions are not members of a class they are just regular functions with special
privileges. In order to make a friend function you have to specify that a particular function is a friend function. This
can be achieved through the following syntax:
class second;
//Forward Declaration
class first
{
private:
int member1;
int membern;
public:
friend void fun( first , second );
//Friend function prototype
};
class second
{
private:
int mem1;
int mem2;
public:
friend void fun( first, second );
};
Page 55
An important note regarding friend functions is that these functions should not be used to relax the access specifiers.
Secondly the friendship of a function is one sided i.e. the function can access the class members but the class cannot
access deceleration that are made inside the function.
4.2 Friend Classes
A friend function has access to those classes with which it is friend. Sometimes a situation arises when we want to
make two classes friends with each other. This means that a class can access the public and private members of
another class directly. To achieve this you must right the friend class statement in the befriending class.
class first
{
private:
friend class second;
int member1;
int membern;
public:
first()
{
member1=10;
member2=20;
}
};
class second
{
private:
int mem1;
int mem2;
public:
void fun( first o1)
{
cout<<o1.member1<<o1.membern;
cout<<mem1<<mem2;
}
};
void main( )
{
first obj1;
second obj2;
obj2.fun( obj1);
Page 56
Find the sum of 1 + 2 + 3 + + arithmetic series. In an arithmetic series the difference between two
consecutive numbers is the same throughout the series. Your class is composed of four data members i.e. the first
entry of the series, last entry of the series, total number of entries for which sum is required and finally the sum up to
n terms which has the formula = 1 + . Use a friend function to compute the sum of the series.
2
public:
series(int f, int n, int e)
{
first=f;
nterm=n;
entries=e;
}
friend void display(series);
};
class sum
{
public:
void series_sum(series &obj)
{
obj.sumn=(obj.entries)*(obj.first+obj.nterm)/2;
}
};
void display(series obj)
//Friend Function body
{
cout<<"The sum of series is "<<obj.sumn<<endl;
}
Page 57
int main()
{
series obj1(6,96,31);
sum obj2;
obj2.series_sum(obj1);
display(obj1);
system ("pause");
return 0;
}
Figure 1: The series class and the sum friend class. The display function is a friend function.
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.
Your task is to create a class named equation which will have the data members a, b and c which are the coefficients
of the quadratic equation. The class will have two more data members namely proot and nroot which stand for the
positive root and negative root of the equation. Suppose that variables a, b and c are integers. Where proot and nroot
are floats.
Construct the class objects by using a nullary constructor.
Then design a friend function which will determine the proot and nroot of the equation.
Create another friend function which will display the values of proot and nroot.
7.2 Practice Task 2
[Expected time = 25 mins]
Your task is to create two classes namely number and computation. The computation class is a friend of the number
class.
The number class will be composed of three floating point data members namely a, b and c. The class will also be
composed of a friend function display that can display all the data members.
The computation class is responsible for performing operations on the number class and hence it has three functions
as follows:
A function to compute the square of sums i.e. + + 2 = 2 + 2 + 2 + 2 + 2 + 2
A function to compute the square of difference i.e. 2 = 2 + 2 + 2 2 2 2
A function to compute the mean of the three numbers
7.3 Practice Task 3
[Expected time = 30 mins]
Create a class called matrix that will find the sum of two matrices. To perform this task you will need to create three
private array data members that will hold the original arrays and an array to hold the sum of the matrices.
Suppose that the size of the matrices is 3x3.
Create a friend function which will add the matrices and store the result in the sum matrix. The sum of two matrices
is the sum of corresponding entries.
7.4 Outcomes
After completing this lab, students will be able explain the difference between a member function and a friend
function. The students will be able to create friend functions and friend classes. Further they will be comfortable
with the manipulation of objects using both friend functions and classes.
7.5 Testing
Test Cases for Practice Task-1
Sample Inputs
a =1;
b =2;
c =-3
Sample Outputs
proot= 1
nroot = -3
Sample Outputs
++
Mean = 2
2
2
=36
= 16
Page 59
2
5
8
Sample Outputs
Results should be as follows.
2
+ = 8
14
3
6
9
4
10
16
6
12
18
Confirmation
Comments
Task No
Description
Marks
4.1
6
7.1
7.2
7.3
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Practice task 2 with Testing
Practice task 3 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
10
5
15
20
25
20
5
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 60
Page 61
Table of Contents
1.
Introduction
63
2.
63
3.
63
4.
Concept Map
63
4.1
4.2
4.3
4.4
4.5
4.6
63
64
64
64
65
66
5.
6.
7.
66
5.1
66
66
6.1
6.2
6.3
66
66
66
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
69
7.1
7.2
7.3
7.4
7.5
69
69
69
70
70
Practice Task 1
Practice Task 2
Practice Task 3
Outcomes
Testing
8.
71
9.
Evaluation Criteria
71
10.
Further Reading
71
10.1
10.2
71
71
Books
Slides
Page 62
Lecture: 13
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 291-308
Activity Name
Evaluation of Design
Setting-up Visual Studio
Walkthrough Tasks
Practice tasks
Evaluation Task
Total Time
25 mins
5 mins
30 mins
70 mins
40 mins
170 Minutes
4. Concept Map
4.1 Introduction to Operator Overloading
Operator overloading is an attractive feature offered to programmers using classes and objects. It allows you to
create class objects and then manipulate them using operators just like variables of primitive data types. For example
we can add two integers by using the plus operator, but what happens when we apply the plus operator to a class
object. Without the help of operator overloading we cannot manipulate class objects using mathematical and logical
operators.
Department of Computer Science,
MAJU
Page 63
Some people have the opinion that operator overloading only makes your class complex and less understandable.
Another opinion which people have is that we do not need operator overloading because we can use typical member
functions to achieve a similar solution. Both of these opinions are greatly flawed, first of all operator overloading
does not increase the complexity of your code because it provides increased understandability and clarity to the
programmer. The second and most important fact is that you could always use regular member functions to create a
similar mechanism but C++ provides you with a proper technique for incorporating operators in your code. Operator
overloading has an added benefit that it allows the user to manipulate objects using proper operator symbols. This
feature cannot be achieved using member functions.
4.2 Which Operators Can Be Overloaded
C++ provides an extended range of operators that can be overloaded. These operators include the conventional
unary operators, mathematical operators, logical operators, stream operators, parenthesis operators and many more.
Because C++ provides such a wide range of operators that can be overloaded, therefore this feature of the language
is widely liked and adopted by programmers.
4.3 Operator Overloading General Rules
Operator overloading allows the programmer to create an operator function that can be used just like any other
function. This means instead of having a textual name for a function your operator function will have a name that is
an operator symbol like +, -, *, / etc.
Before we begin with operator overloading one must memorize some standard rules. The rules are as follows
Only those operators can be overloaded that have been defined by C++. This means you cannot create your own
operators. For example will not qualify as an operator.
It is not necessary that you overload the entire set of operators for a class. You only overload those that will be
used in your program.
In a single expression you can use multiple operators but the order of precedence defined by the language
cannot be changed.
If an operator is unary by nature then it cannot be converted to binary and vice versa.
When you overload an operator it is purely your choice what comes in the operator function body. This means
you may be using the + operator but in the function body you can perform the / operation. Of course this is a
logical wrong and such things should be prevented. Hence defining the operator is purely up to the programmer.
4.4 Operator Overloading Syntax
As explained previously, operator overloading is basically a function that has an operator symbolic name. The
operator function is created inside the class and it is used basically in the main. The code snippet below shows the +
operator being overloaded. The parameter is actually an object of the class because this operator is a binary operator
that requires one calling object and one object being passed as an argument. The return type of this function is
dependent on what you wish to return. If you are computing an expression having more than two objects then you
will need to create a temporary object and return the object for further computing of the expression. Refer to the
walkthrough task in this lab.
int operator + (classname obj)
//The plus operator
{
. . .
}
Similarly the code snippet below shows the pre increment operator being overloaded.
int operator ++ ( )
//The pre increment operator
{
. . .}
Similarly the code snippet below shows the post increment operator being overloaded. The parameter is in fact never
passed; it is just an indicator to show that this function is a post increment operator. Hence whenever there is an
operator with a unary operator then it indicates that you are referring to a post increment operator.
int operator ++ (int n)
//The post increment operator
{
. . . }
Department of Computer Science,
MAJU
Page 64
Page 65
Page 66
Page 67
Figure 1: The toll class demonstrating the use of various overloaded operators
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.
Page 68
Your task is to overload the prefix and postfix increment operators for a class called roundoff. The roundoff class
has a floating point data member called number. Overload the operators as follows.
Overload the stream insertion and extraction operators to input/ output the data.
Prefix increment When this operator is called there will be an increment in the integer part of the number. For
example if our original number is 3.5 then after prefix increment the result will be 4.5
Postfix increment - When this operator is called there will be an increment in the fractional part of the number.
For example if our original number is 3.5 then after postfix increment the result will be 3.6.
7.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.
7.5 Testing
Test Cases for Practice Task-1
Sample Inputs
obj1= 10
obj2= 20
obj3= 40
obj4= 20
obj5= 30
obj6= 20
Provide any value for fuel
Sample Outputs
The average distance covered is 23.33
Obj1+obj2+obj3+obj4+obj5+obj6/6
Test Cases for Practice Task-2
Sample Inputs
obj1.numerator = 1
obj1.denominator = 2
Sample Outputs
Sum = obj1 + obj2 =
obj2.numerator = 3
obj2.denominator = 2
4
2
Product = obj1*obj2 =
-2
2
3
4
Sample Outputs
After post increment result is 9.6
After pre increment result is 10.6
Confirmation
Comments
Page 70
Task No
Description
Marks
4.1
6
7.1
7.2
7.2
8
Problem Modelling
Procedures and Tools
Practice task 1 with Testing
Practice task 2 with Testing
Practice task 3 with Testing
Evaluation Tasks (Unseen)
Good Programming
Practices
Total Marks
10
5
20
25
15
20
5
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 71
Page 72
Table of Contents
1.
Introduction
74
2.
74
3.
75
4.
Concept Map
75
5.
75
5.1
5.2
75
76
6.
7.
76
6.1
6.2
6.3
76
76
76
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
78
7.1
7.2
7.3
7.4
78
78
79
79
Practice Task 1
Practice Task 2
Outcomes
Testing
8.
79
9.
Evaluation Criteria
79
79
Books
Slides
79
79
Page 73
Lecture: 15 and 16
Textbook: Object-Oriented Programming in C++; Author: Robert Lafore, Fourth Edition
o Pages: 372 428
Total Time
5 mins
30 mins
80 mins
55 mins
170 mins
Page 74
4. Concept Map
Inheritance is one of the most important building blocks of OOP. The concept of reusable classes is helpful to
manage objects. You can create new classes (derived classes) that are able to inherit certain attributes and behavior
of their ancestor or base class(es). Prior to working with inheritance, it is important to consider the following aspects
of inheritance.
Inheritance represents is-a relationship in OOP i.e. any specific object is a type of a more general class of
object. For example, Train is a type of Vehicle
By design, a derived class should inherit all attributes and behaviors of its base class(es)
While declaring its own data fields a derived class can extend the features of its base class(es)
While defining new functionality, a derived class can modify the behavior provided by the base class(es)
Inheritance in OOP saves a lot of work and time. You can save additional work as some of the object
definitions(class) already exists. Time saving is due to the reason that much of the code has already been written and
tested.
Page 75
Page 76
.
Figure 1: Base and Derived Classes
Page 77
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:
\\dataserver\assignments$\OOP\Lab08
7.1 Practice Task 1
[Expected Time = 40 mins]
Consider a base class named Employee and its derived classes HourlyEmployee and PermanentEmployee while
taking into account the following criteria.
Employee class has two data fields i.e. a name (of type string) and specific empID (of type integer)
Both classes (HourlyEmployee and PermanentEmployee) have an attribute named hourlyIncome
Both classes (HourlyEmployee and PermanentEmployee) have three-argument constructor to initialize
the hourlyIncome as well as data fields of the base class
Class HourlyEmployee has a function named calculate_the_hourly_income to calculate the income of an
employee for the actual number of hours he or she worked. One hour income is Rs. 150
Similarly, PermanentEmployee class has function named calculate_the_income to calculate the income of
an employee that gets paid the salary for exact 240 hours, no matter how many actual hours he or she
worked. Again, one hour salary is Rs. 150.
Implement all class definitions with their respective constructors to initialize all data members and functions to
compute the total income of an employee. In the main() function, create an instance of both classes (i.e.
HourlyEmployee and PermanentEmployee) and test the working of functions that calculate total income of an
employee.
7.2 Practice Task 2
[Expected Time = 40 mins]
Consider a class BankAccount that has
Two attributes i.e. accountID and balance and
A function named balanceInquiry() to get information about the current amount in the account
Derive two classes from the BankAccount class i.e. CurrentAccount and the SavingsAccount. Both classes
(CurrentAccount and SavingsAccount) inherit all attributes/behaviors from the BankAccount class. In addition,
followings are required to be the part of both classes
Appropriate constructors to initialize data fields of base class
A function named amountWithdrawn(amount) to withdraw certain amount while taken into account the
following conditions
o While withdrawing from current account, the minimum balance should not decrease Rs. 5000
o While withdrawing from savings account, the minimum balance should not decrease Rs. 10,000
amountDeposit(amount) to deposit amount in the account
In the main() function, create instances of derived classes (i.e. CurrentAccount and SavingsAccount) and invoke
their respective functions to test their working.
Page 78
7.3 Outcomes
After completing this lab, student will be able to understand the implementation and design of Inheritance in C++.
7.4 Testing
For both Practice Tasks, lab instructor must examine
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 3: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Time
Marks
10
55
20
5
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 79
Page 80
Table of Contents
1.
Introduction
82
2.
83
3.
83
4.
Concept Map
83
5.
84
5.1
5.2
84
84
6.
7.
85
6.1
6.2
6.3
85
85
85
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
86
7.1
7.2
7.3
7.4
7.5
86
87
87
87
87
Practice Task 1
Practice Task 2
Practice Task 3
Outcomes
Testing
8.
88
9.
Evaluation Criteria
88
88
Books
Slides
88
88
Page 81
};
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:
};
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:
};
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.
Page 82
Lectures: 17, 18
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 372 - 428
Activity Name
Setting-up Visual Studio
Walk-through Tasks
Practice tasks
Evaluation Task
Activity time
5 mins
30 mins
25 mins for task 1 and 2
35 mins for task 3
50 min for all assigned task
Total Time
Total Time
5 mins
30 mins
85 mins
50 mins
170 mins
4. Concept Map
Inheritance is one of the most important building blocks of OOP. The concept of reusable classes is helpful to
manage objects. You can create new classes (derived classes) that are able to inherit certain attributes and behavior
of their ancestor or base class(es). Prior to working with inheritance, it was important to consider that data
member(s) should have private access and only through public member functions, you can access data members of a
class. However, with inheritance, it is sometimes required to have an intermediate level of accessibility to classs
data member(s) that exists only within inheritance class hierarchy but not outside these classes.
C++ provides intermediate level of accessibility through protected access specifier. Data member(s) of a base class
with protected accessibility are only be directly accessible within base class and all of its derived classes but not in
other parts of the program. Nevertheless, you should be careful while making data field(s) protected. Use protected
access only where you think that derived classes will use base class data field(s). The access of protected data
members in the derived classes make them less secure than private data members.
Moreover, access specifiers also play their role in the inheritance process. Considering access specification in C++,
inheritance can be private, protected, or public. The effects of access specifiers in inheritance process on derived
classs member(s) are different as illustrated in Table 2.
Table 2: Inheritance access specifiers and their effect on derived class members
Private
Protected
Public
Page 83
Page 84
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.
Page 85
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:
\\dataserver\assignments$\OOP\Lab09
7.1 Practice Task 1
[Expected Time = 25 mins]
NoteBook is the base class that holds
data fields named manufacturerID (of integer type) and manufacturerName (of string type)
A two-argument constructor to initialize data-fields with user-defined values
Appropriate accessor and mutator functions to set and get values of data fields
Derive two classes from the NoteBook class:
ENotebook, which contains an attribute size of integer type and a setter member function to set size value
PaperNoteBook, which contains an instance variable named totalPages along with a member function to
set total number of pages in a certain paper notebook object
Both derived classes have function display to show all data field values (including values inherited from the
base class).
In the main() function, create objects of ENoteBook and PaperNoteBook classes and show the advantages of using
protected access specifier.
Page 86
A function named totalCharges that returns total cost of an order (including serviceFee + price of food
item(s) served)
A parameterized constructor, which requires arguments for all of its own data fields as well as for the data
fields of base class
A member function named display() to show all the details of an order including orderID, price, and
totalCharges
In the main() function, instantiate an object of class StaffService object and test the implementation of both classes
through this object.
7.4 Outcomes
After completing this lab, student will be able to understand the implementation and design of inheritance as well as
the use of protected access specifier in inheriting classes.
7.5 Testing
For all Practice Tasks, lab instructor must examine
the implementation of all mentioned classes
the creation of instances of specified classes
the invocation of specified functions
Department of Computer Science,
MAJU
Page 87
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Marks
10
55
20
5
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 88
Page 89
Table of Contents
1.
Introduction
91
2.
92
3.
92
4.
Concept Map
92
5.
93
5.1
5.2
93
93
6.
7.
93
6.1
6.2
6.3
93
93
94
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
95
7.1
7.2
7.3
95
96
96
Practice Task 1
Outcomes
Testing
8.
96
9.
Evaluation Criteria
96
97
Books
Slides
97
97
Page 90
Single Inheritance: a single child class derived from a single base class
Hierarchical Inheritance: multiple child classes derived from a single base class
Multi-level Inheritance: a single derived class inherited from another derived class
Multiple Inheritance: a single derived class inherited from more than one base classes
Hybrid Inheritance: any legal combination of more than one type of inheritance
In particular, the main focus of this lab is concerned with the understanding of multi-level and multiple inheritance.
Multi-level represents the scenario of inheriting attributes and behavior of a class that is already inheriting attributes
and behaviors from other class(es). The syntax of writing C++ code to implement multi-level class hierarchy is
given as under:
class X
{
// code statements go here
};
class Y: public X
{
//code statements go here
};
class Z: public Y
{
//code statements go here
};
...
There is no limitation on the number of levels in multi-level inheritance.
Multiple Inheritance represents where a single class inherits attributes and behaviors from more than one class. The
syntax to write C++ code for multiple inheritance is given as under:
class X
{
// code statements go
};
class Y
{
//code statements go
};
class Z: public X, public
{
//code statements go
};
here
here
Y
here
Page 91
Lectures: 19, 20
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 399- 412
Activity Name
Setting-up Visual Studio
Walk-through Tasks
Practice tasks
Evaluation Task
Activity time
5 mins
30 mins
80 mins
55 min for all assigned task
Total Time
Total Time
5 mins
30 mins
80 mins
55 mins
170 mins
4. Concept Map
Inheritance is one of the most important building blocks of OOP. The concept of reusable classes is helpful to
manage objects because occasionally it happens that a class may have some features that it can derive from already
existing class(es). Hence, with inheritance, it is sometimes crucial to build multi-level class hierarchies or to derive
class(es) from multiple existing classes. To grasp the concept and need of multi-level and multiple inheritance,
consider the following class hierarchy
Person
Employee
Administration
Student
Academic
Dean/HOD
Figure 1: Class Hierarchies showing Multi-level and Multiple Inheritance
A person can be an employee or a student. An employee may have rights of admin officer or of academic officer.
These class hierarchies represent multi-level inheritance. However, a Dean or Head of Department (HOD) may have
rights to modify the status already defined by an admin or academic officer. This type of relationship between
classes is an example of multiple inheritance.
C++ facilitates users while supporting the implementation of both multi-level and multiple inheritance. There is no
limitation on the number of levels in multi-level inheritance and there is no limitation on the number of parent
classes from which a child can be derived. Nevertheless, as a good practice, it is recommended to restrict levels and
number of base classes to two in multi-level and multiple inheritance.
Department of Computer Science,
MAJU
Page 92
Page 93
Page 94
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:
\\dataserver\assignments$\OOP\Lab10
7.1 Practice Task 1
[Expected Time = 80 mins]
Consider the following details of all classes for class hierarchy shown in Figure 1 of this lab.
Page 95
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.
7.2 Outcomes
After completing this lab, student will be able to understand the implementation and design of Multi-level and
Multiple Inheritance in C++.
7.3 Testing
For Practice Task 1, while inspecting implementation of classes, lab instructor must ensure that student has
taken hold the concept of multi-level and multiple inheritance. Furthermore, it is required to check the
invocation of all functions with the created instances of all mentioned classes.
Table 3: Practice Tasks Confirmation
Practice Tasks
T1
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Department of Computer Science,
MAJU
Marks
10
55
20
5
10
100
Page 96
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 97
Page 98
Table of Contents
1.
Introduction
100
2.
100
3.
101
4.
Concept Map
101
5.
101
5.1
5.2
101
102
6.
7.
102
6.1
6.2
6.3
102
102
102
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
104
7.1
7.2
7.3
7.4
104
104
105
105
Practice Task 1
Practice Task 2
Outcomes
Testing
8.
105
9.
Evaluation Criteria
105
105
Books
Slides
105
105
Page 99
Lectures: 21, 22
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 188-193, 382-392
Department of Computer Science,
MAJU
Page 100
Activity Name
Setting-up Visual Studio
Walk-through Tasks
Practice tasks
Evaluation Task
Activity time
5 mins
30 mins
50 mins for task 1
30 mins for task 2
55 min for all assigned task
Total Time
Total Time
5 mins
30 mins
80 mins
55 mins
170 mins
4. Concept Map
Function overloading and function overriding are the two key concepts of a number of modern computer
programming languages.
Overloaded functions provide specific functionalities while taking into account the type/number of parameter(s) they
receive and the fundamental advantage is the cleanliness of code. For example, in the absence of overloading, a
computer program may have several functions with different names to calculate the area of a geometric shape as
shown below:
class
GeometricShape{
public:
int squareArea(int sideLength);
int reactangleArea(int length, int width);
int triangleArea(int side1, int side2, int side3);
};
However, the same code with function overloading would be as
class
GeometricShape{
public:
int area(int sideLength);
int area(int length, int width);
int area(int side1, int side2, int side3);
};
On the other hand, function overriding is the ability of redefining a specific behavior (function) of a base class
within derived class(es). Besides the provisioning of a specific modified implementation of a base class function,
function overriding is used to perform runtime polymorphism.
Page 101
In this task, you are required to write a C++ code which would elaborate function overloading. The following lines
show the output of a basic function overloading concept:
6.3.1 Writing Code
In the source file, which is created in the project FunctionOverloading write following C++ code:
Page 102
Page 103
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below:
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:
\\dataserver\assignments$\OOP\Lab11
7.1 Practice Task 1
[Expected Time = 50 mins]
Create a class named GeometricShape containing
Two data fields i.e. shapeType (a string) and area (of type double)
A no-argument constructor to initialize all data fields with default values NoShape and 0.0
A member function named computeArea() with returning value of area data field
A member function named show() to display the details associated with an instance of this class
Derive a class named Rectangle from class GeometricShape that includes
data members for the length and width of a rectangle,
respective mutator and accessor functions to set and get values of length and width, and
overriding function named computeArea() to compute the area of rectangle (length x width)
overriding function named show() to display the details associated with an instance of class Rectangle
From the Rectangle class, derive a class named Cuboid that contains
a data field named height in addition to length and width,
two functions named setHeight and getHeight() to set and get value of height data field, and
an overriding function named computeArea() to calculate the area of a cuboid (length x width x height)
overriding function named show() to display the details associated with an instance of class Cuboid
Implement these classes and in the main() create instances of each class and test the functionality of overridden
member functions with these instances.
7.2 Practice Task 2
Page 104
A parameterized constructor to initialize data members that they inherit from the class
MusicalInstrsument
In the main(), create instances of MusicalInstrument, Flute and Guitar classes. Invoke displayPrice() with
MusicalInstrument object while passing references of Flute and Guitar instances.
7.3 Outcomes
After completing this lab, student will be able to understand the difference between function overloading and
function overriding within a class or class hierarchies.
7.4 Testing
For Practice Task 1, lab instructor must confirm the implementation of classes i.e. GeometricShape,
Rectangle, and Cuboid. With instances of each class, test the invocation of proper overridden function.
For Practice Task 2, lab instructor ensures the invocation of displayPrice() function with the
MusicalInstrument instance while receiving references of the instances of Flute and Guitar classes.
Table 3: Practice Tasks Confirmation
Practice Tasks
T1
T2
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Marks
10
55
20
5
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Department of Computer Science,
MAJU
Page 105
Page 106
Table of Contents
1.
Introduction
108
2.
110
3.
110
4.
Concept Map
110
5.
110
5.1
5.2
110
111
6.
7.
111
6.1
6.2
6.3
111
111
111
Tools
Setting-up Visual Studio 2008
Walk-through Task
Practice Tasks
113
7.1
7.2
7.3
7.4
113
113
114
114
Practice Task 1
Practice Task 2
Outcomes
Testing
8.
114
9.
Evaluation Criteria
114
114
Books
Slides
114
114
Page 107
Page 108
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 classs object only destructor of base class would be called.
Virtual Base Classes:
Virtual base classes can be used to avoid diamond problem of multiple inheritance that is explained as under.
class Base
{
protected:
void func()
{ cout<<A Base Class Function; }
};
class Derived1: public Base{
};
class Derived2: public Base{
};
class Derived3: public Derived1, public Derived2
{
};
In the code above, both (Derived1 and Derived2) classes contain a copy of func(), which is inherited from class
Base. Upon the invocation of func() with an object of Derived3 class, compiler would be unable to decide which
copy to use.
To overcome this situation, it is required to use virtual keyword with base class inheritance. Hence, the above code
would be implemented as
class Base
{
protected:
void func()
{ cout<<A Base Class Function; }
};
class Derived1: virtual public Base{
};
class Derived2: virtual public Base{
};
class Derived3: public Derived1, public Derived2
{
};
Pure Virtual Function and Abstract Class:
You may have observed that with any class hierarchy in OOP, derived class(es) become more specific version of
base class(es) which are more general or abstract. It is sometime good in practice to make the base class as abstract
class that contains only the most common features of all of its derived classes. In C++, you can make base class an
abstract class by declaring a pure virtual function in it. The syntax is given as under:
class Base
{
protected:
virtual void func() = 0;
};
Instantiation of an abstract class is not possible and you should override pure virtual function in derived class(es).
Page 109
Total Time
5 mins
30 mins
80 mins
55 mins
170 mins
4. Concept Map
Following encapsulation and inheritance, polymorphism is the third important capability of OOP paradigm. The
fundamental inspiration behind polymorphism is that of dynamic binding. In this way, at compile time, compiler
knows nothing about which function to call. On the contrary, decision is made at runtime. Polymorphism helps
programmer to make program in general rather than specific. In simple words, it provides a single interface with
different implementations. Moreover, polymorphism facilitates program extensibility while permitting new derived
classes and functions to be added to an inheritance hierarchy without modifying application programs that already
utilize various interfaces of that inheritance hierarchy. However, for beginners, it is difficult to grasp and implement
the concept of polymorphism, dynamic binding, and abstract classes.
Page 110
In this task, you are required to write a C++ code which would elaborate polymorphism concept. The following lines
show the output of a basic polymorphism concept:
6.3.1 Writing Code
In the source file, which is created in the project Polymorphism write following C++ code:
Page 111
Figure 1: Polymorphism
Page 112
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below:
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:
\\dataserver\assignments$\OOP\Lab12
7.1 Practice Task 1
Consider an abstract class Computer having
Two fields (i.e. companyName, price) and
A single function named show()
A class named Desktop inherits Computer class and adds fields representing
color, monitor size, and processor type and
Override function named show() to display values of its all attributes
A class named Laptop inherits Computer class and adds fields representing
color, size, weight, and processor type and
Override function named show() to display values of its all attributes
Write a main() function that instantiates objects of derived classes to access respective show() function using
dynamic binding.
7.2 Practice Task 2
Create a class named Person, which contains
A pure virtual function named print()
Two data fields i.e. personName and age
Page 113
In the main function, create instances of derived classes to access respective print() function using dynamic
binding.
7.3 Outcomes
After completing this lab, student will be able to implement the concepts of virtual functions, dynamic binding, pure
virtual function, and abstract classes.
7.4 Testing
For Practice Task 1, it is required to check the assignment of derived class instances to base class pointer.
Moreover, (while considering the dynamic binding) test the invocation of respective show() function.
For Practice Task 2, it is required to check the assignment of derived class instances to base class pointer.
Moreover, (while considering the dynamic binding) test the invocation of respective print() function.
Table 3: Practice Tasks Confirmation
Practice Tasks
T1
T2
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Marks
10
55
20
5
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 114
Page 115
Table of Contents
1.
Introduction
117
2.
118
3.
118
4.
Concept Map
118
5.
119
5.1
5.2
119
119
6.
7.
119
6.1
6.2
6.3
119
119
120
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
121
7.1
7.2
7.3
121
122
122
Practice Task 1
Outcomes
Testing
8.
122
9.
Evaluation Criteria
122
122
Books
Slides
122
122
Page 116
Lectures: 27, 28
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 414- 420
Page 117
Activity Name
Setting-up Visual Studio
Walk-through Tasks
Practice tasks
Evaluation Task
Activity time
5 mins
30 mins
80 mins for assigned task
55 min for all assigned task
Total Time
Total Time
5 mins
30 mins
80 mins
55 mins
170 mins
4. Concept Map
Primarily two tasks are the part of each object-oriented design i.e. identification of object types within the problem
domain and relationship modeling between the existing object types. Three kinds of relationships are usually exist
between identified objects i.e.
The is-a relationship exhibits a relationship between an object of specific type to its general type. For example, a bus
is-a vehicle, an employee is-a person, circle is-a geometric shape etc. The is-a relationship has been modeled in
terms of inheritance that you have already studied in Lectures 15-18.
The uses-a relationship demonstrate that an object of one specific type uses an object of different type to perform
some activity. For example, a person uses-a wiper to wash bus window pane, a teacher uses-a course to teach
student, a cyclist uses-a pump in tire-pumping activity). The uses-a relationship can be described as association
between objects i.e. a teacher has association with student through a specific course. Similarly, university has
association with its departments through administration. In simple words, association is a relationship between
objects where exists no ownership and each object has its own lifecycle. More specifically, association are of two
types i.e. aggregation and composition that represents has-a relationship between objects.
The has-a relationship represents a classical ownership of whole-part relationship. Sometimes an object of one type
contains an object of type e.g. a university has-a number of departments and ultimately a department has a number
of professors, a bus has-an engine, a bike has-a set of wheels etc. The has-a relationship can be modeled as
aggregation and composition.
Aggregation is type of association representing weak relationship. In aggregation, contained object exists even
after the release of an owning object. Hence, in aggregation, there exists ownership without life-cycle
dependency. For example, if a company no longer exists even then employee of that will continue to exist.
Composition is a special type of aggregation representing strong relationship in which the life-cycle of the part
is dependent on the whole. Existence of the part is directly dependent on the existence of the whole. For
example, the relationship between vehicle and its engine. Engine is build and destroyed whenever a vehicle is
build or destroyed, respectively.
Page 118
Page 119
Page 120
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below:
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:
\\dataserver\assignments$\OOP\Lab123
7.1 Practice Task 1
[Expected Time = 80 mins]
Consider six classes i.e. Person, Professor, Researcher, Department, Laboratory, and University having following
specifications.
Class University has
Two attributes of type string i.e. universityName and location
An attribute named dept of type Department
Class Department has
Two attributes i.e. deptID, deptName
A two-argument constructor to initialize data fields with user-defined values
A member function display() to show all attribute values
Class Laboratory contains
Two attributes i.e. labID and experimentNo
A two-argument constructor to initialize data member with user-defined values
Class Person has
Two attributes i.e. name and age
A parameterized constructor to initialize attributes with user-defined values
A member function display() to show its attribute values
Class Professor is derived from class Person and has
A data field named profName of type string
A data field named dept of type Department
A two-argument constructor to initialize both attributes of user-defined values
Class Researcher is derived from class Professor and has
An additional attribute named lab of type Laboratory
A constructor to initialize lab with user-defined value
Department of Computer Science,
MAJU
Page 121
a)
Draw UML diagram for each class and show inheritance, aggregation, and composition relationship
between these classes.
b) Implement all these classes while illustrating the concept of aggregation and composition in terms of
ownership and life-cycle.
7.2 Outcomes
After completing this lab, student will be able to implement the concepts of association, aggregation, and
composition in terms of ownership and life cycle of associated objects.
7.3 Testing
For Practice Task 1, Lab instructor must verify the implementation and required relationships among all
classes and objects. In addition, it is required to confirm that code has clearly elaborated the concept of
aggregation and composition in terms of ownership and life cycle.
Table 3: Practice Tasks Confirmation
Practice Tasks
T1
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Marks
10
55
20
5
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 122
Page 123
Table of Contents
1.
Introduction
125
2.
126
3.
126
4.
Concept Map
126
5.
126
5.1
126
6.
7.
127
6.1
6.2
6.3
127
127
127
Tools
Setting-up Visual Studio 2008
Walkthrough Task
Practice Tasks
128
7.1
7.2
7.3
7.4
7.5
128
128
128
129
129
Practice Task 1
Practice Task 2
Practice Task 3
Outcomes
Testing
8.
129
9.
Evaluation Criteria
129
130
Books
Slides
130
130
Page 124
T>
}
You can call this function in different ways i.e. with parameters of types int, long, float, double as:
int
double
var3 = 10.0;
TE1;
TE2;
It is clear from above examples that prior to coding a function template or class template you have to provide
template definition statement starting with the keyword template. This template reserved word in C++ informs the
compiler that programmer is going to define a function or class template. Further, the variable with reserved word
class or typename within angle brackets (< >) is known as the template argument. This template argument is
replaced with specific data type with each function call statement.
Page 125
Activity Name
Setting-up Visual Studio
Walk-through Tasks
Practice tasks
Evaluation Task
Activity time
5 mins
30 mins
25 mins each for task 1 and 2
40 mins for task 3
45 min for all assigned task
Total Time
Total Time
5 mins
30 mins
90 mins
45 mins
170 mins
4. Concept Map
To deal with overloaded functions and various classes (that differ from each other in terms of the types of data
fields), C++ assists programmer to define generic functions and classes while using the concept of templates. It is
important to mention here that templates do not save the amount of memory to be used by different functions or
class objects. However, template approach (that is a very special kind of code reusability) saves the time of writing
multiple functions and classes with same logical task. In this way, later on, modification(s) can be performed easily
while changing code at one place instead of multiple places.
The statement of template definition in C++ code by itself is not able to generate any code. Code generation for a
specific template function takes place at the time of function invocation. This is due to the fact that upon function
invocation compiler comes to know about the type to substitute template parameter. This is known as instantiating
the function template.
Concerning class templates in C++, it is important to point out here that C++ provides a powerful and versatile
collection of functions and classes for common data structures i.e. vector, stack, queue etc. This collection of classes
is known as Standard Template Library (STL). Functions and classes in STL provides well-organized and extensible
framework to develop certain applications.
Page 126
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.
Page 127
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
6.3.3 Executing the Program
A sample output after running the program is shown below:
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:
\\dataserver\assignments$\OOP\Lab14
A single data member as an array named stack of size 50 to store certain elements
A constructor to initialize stack with value 0 or 0.0 at all its indexes
Three member functions i.e. push(type) to add elements in the Stack, pop() to remove elements from the
stack, and currentStatus() to check whether the array is filled or not. (A filled array is an array that has
non-zero value at all of its indexes).
In the main() function, create three objects with different data types of class GeneralStack and test the functionality
of member functions for various values of data members for these objects.
Page 128
7.4 Outcomes
After completing this lab, student will be able to understand the use and working of function and class templates in
C++.
7.5 Testing
1.40
Sample Outputs
29
Sample Outputs
78.5
78
200.0
200
For Practice Lab 3, lab instructor should check the creation of three instances of GeneralStack class while
each having an array of different data type. Moreover, check the required functionality of member
functions with these instances.
Table 3: Practice Tasks Confirmation
Practice Tasks
T1
T2
T3
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Department of Computer Science,
MAJU
Marks
10
55
20
5
10
100
Page 129
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 130
Page 131
Table of Contents
1.
Introduction
133
2.
133
3.
134
4.
Concept Map
134
5.
134
5.1
5.2
134
135
6.
7.
135
Tools
6.1
Setting-up Visual Studio 2008
6.2
Walkthrough Task
135
135
135
Practice Tasks
137
7.1
7.2
7.3
7.4
7.5
137
137
137
137
138
Practice Task 1
Practice Task 2
Practice Task 3
Outcomes
Testing
8.
138
9.
Evaluation Criteria
138
138
Books
Slides
138
138
Page 132
Lecture: 32
Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 703 - 720
Activity Name
Setting-up Visual Studio
Walk-through Tasks
Practice tasks
Evaluation Task
Activity time
5 mins
25 mins
30 mins for each task
50 min for all assigned task
Total Time
Total Time
5 mins
25 mins
90 mins
50 mins
170 Mins
Page 133
4. Concept Map
To deal with anomalous or exceptional situation in the running code, programming languages facilitate programmers
with the provisioning of exception handling mechanism. At present, C++ provides try-catch block to handle
exception. However, to handle exceptions, older C++ programs use the logic with decision statements (i.e. if-else or
switch statements). As an example, pseudocode to exception handling in older C++ is given as under:
Execute statement(s)
If error occurs, do some error processing
Else execute next statements
If error occurs, do some error processing
Else execute next statements
...
Due to a number of reasons, this type of approach has various shortcomings as explained under:
error detection/handling logic is intermingled with the program logic
it is difficult to read the program
due to constant decision testing for rare exceptional circumstances, program execution becomes less
efficient
Although, exception handling mechanism using try-catch block is an advantage over if-else construct but it is not a
recommended practice to use try-catch block for simple errors that are already expected within a program. These
types of errors should be handled locally. Hence, you should not overuse catch block because usually exceptions are
permitted to propagate up the call stack. It is also important to consider the order of exceptions that are defined in
catch blocks. It is essential to use a catch block with a derived class type before the catch block with base class type.
Page 134
A member function named getValues is required to get values for both data fields. If the entered price would be less
than Rs. 2000 or greater than Rs. 8000, then entered price will be thrown as an exception. Exception must be caught
within the getValues function to show some appropriate message. In the main() function, create three objects of
Fan class and test the code for entries of all three objects.
5.2.2 Task-2
Create a class RealEstate that contains
The main() function must catch all exceptions (i.e. invalid house location if it is any character other than S, N, W, or
E, invalid house price if it is less than Rs. 100,000, and invalid roomCount for any value less than equal to zero)
generated from setter functions (i.e. setHouseNo, setHousePrice, setRoomCount).
Page 135
Page 136
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:
\\dataserver\assignments$\OOP\Lab15
7.1 Practice Task 1
[Expected Time = 30 mins]
In class MyWork, define an inner class named MyException having a function why() with display statement
Because of Exception. Throw an exception of inner class type in a function named myFunction() in the outer
MyWork class. Test this type of exception handling in the main() function.
7.2 Practice Task 2
[Expected Time = 30 mins]
Define a custom exception class named SecureArray having array of int type as single data member and let the
insert and delete functions of this class to throw OutBoundException (your own defined exception class) if the
array is already full or already empty, respectively. In the main() function, write a try-catch block to handle this
type of exception.
7.3 Practice Task 3
[Expected Time = 30 mins]
Create a class named LCD with
data members for modelNo (of string type), screenSize (of int type), and itemPrice (of float type)
a no-argument constructor that initializes all three data members with values empty, 0, and 0.0,
respectively
an inner class named AnExcep containing a member function what() with an appropriate message
providing information about exception type
three member functions namely setModelNo, setScreenSize, and setItemPrice to modify the values for data
members
three member functions namely getModelNo, getScreenSize, and getItemPrice that returns modelNo,
screenSize, and itemPrice, respectively.
In the main() function, create three objects of type LCD and test the class implementation for various values of data
members for these objects. Exceptions of inner class types would be thrown and caught in main() while following
the criteria that if model number is not started with character V, if screen size entered is not between 30 and 55, or
if the price entered is a negative number or a value greater than Rs. 90,000.
7.4 Outcomes
After completing this lab, student will be able to throw and handle exceptions (using try-catch block) in a C++
program.
Page 137
7.5 Testing
Lab instructor must consider the following:
For Practice Task 1, test the exception generation of inner class type and its handling in the main()
function.
For Practice Task 2, test that exceptions generated/thrown in insert and delete functions must be handled
within the main().
For Practice Task 3, test the working of exception handling mechanism with single try block having
multiple associated catch blocks to handle a relevant thrown exception message.
Table 3: Practice Tasks Confirmation
Practice Tasks
T1
T2
T3
Confirmation
Comments
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).
Table 4: Evaluation of the Lab
Sr. No.
1
2
3
4
5
Task No
6
7.1
Description
Procedures and Tools
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Total Marks
Marks
10
55
20
5
10
100
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
Page 138
Annexure A
Course Outline
Week#
Lecture#
Lecture 1
1
Lecture 2
Lecture 3
2
Lecture 4
Lecture 5
Lecture 6
Lecture 7
Lecture 8
Lecture 9
5
6
8
9
10
11
12
13
14
15
16
Lecture 10
Lecture 11
Lecture 12
Lecture 13
Lecture 14
Lecture 15
Lecture 16
Lecture 17
Lecture 18
Lecture 19
Lecture 20
Lecture 21
Lecture 22
Lecture 23
Lecture 24
Lecture 25
Lecture 26
Lecture 27
Lecture 28
Lecture 29
Lecture 30
Lecture 31
Lecture 32
Topic
- Introduction of the Course
- Overview of Structured Programming in C++
- Function Revision (Call by Value, Call by Reference, Call by Pointer)
- Pointer Revision
- Object-Oriented Concepts (Introduction to Classes and Objects)
- Data Members and Member Functions
- Constant Member Functions
- Use of Access Specifiers (public, private) - (Scope of class members)
- Concept of Constructor and Object Instantiation
- Importance of Destructor
- Constructor Overloading
(No-argument Constructor, Parameterized Constructor)
- Introduction to copy constructors
- Shallow Copy and Deep Copy
- Array as class data members (Initializing array with constructors)
- Static and Dynamic Arrays, Array of Objects
- Friend Functions
- Friend Classes
- Operator Overloading - (Unary and Binary Operator Overloading)
- Assignment Operator Overloading
(Difference between Assignment Operator and Copy Constructor)
- Stream Insertion and Extraction Operator Overloading
- Introduction to Inheritance in OOP
- Constructor and Destructor Chaining
- The protected access specifier
- Types of Inheritance
- Class Hierarchies (Multi-level Inheritance)
- C++ Multiple Inheritance
- Function Overloading and Function Overriding
- Object as argument to the Function
- Pointer to Objects
- Introduction to Polymorphism in OOP
- Virtual Functions
- Pure Virtual Functions and Abstract Base Classes
- Virtual Inheritance
(The Diamond Problem and its Solution)
- Relationships in OOP - (Association, Aggregation, and Composition)
- Life Cycle and Ownership of Objects
- Function Templates
- Class Template Specialization
- Standard Template Libraries
- Exception Handling
Page 139
Annexure B
Good Programming Practices
This section presents you some of the well known good programming practices. You will be evaluated based on
these practices in all your tasks.
Generic Programming Practices
Always use indentation. Your code should clearly state the start and end of the if-statements, loopstatements, switch statements etc.
Always use meaningful variable names, do not use the general name of variables such as: a, b, x etc.
For example, you want to declare a variable to store the marks obtained by a student, you may think of
using the name of this variable as std_marks.
Always use consistent variable names in your code for things that are similar. For example you want to
store student-marks and student-names. And for student marks you have already defined std_marks, now
if you define the student-name to store student name. This will not remain consistent although
std_name is also a valid and good logical name.
Same rule applies for function names. Make sure that function names are meaningful and convey their
purpose.
Always use proper comments to each line/ section. For example what a particular line is doing, what a
particular loop, if-statement is doing. This will help other people and yourself in understanding the code.
Always select a proper data type to store a particular data. For example, storing the status of student as
pass or fail, you may consider the data type of Boolean, instead of using int variable which will be
excessively larger data type to store such values.
Write only one statement per line.
Try to create many member functions and avoid creating a single member function that will set or get
values for a large number of variables.
When you create constructors make sure that you create both the nullary and the parameterized constructor.
Try to use the destructor as a cleanup mechanism.
Overload functions where possible. This increases flexibility of code.
Do not use friend functions as a technique for bypassing data hiding and encapsulation.
Do not use inheritance between classes that can have no relation between them.
Do not use exception handling as a method for non exception based programming.
Page 140