Solutions
Lab 1-1: Installation and usage of Dev-C++ and online
compilers
Objective:
The objective of this lab is to teach students how to install and use the Dev-
C++ and online compilers.
Learning Outcomes:
After this lab, the students will be able to run the C++ code in Dev-C++ and
the online compilers.
Problem Statement
You are required to install any version of Dev-C++ in your system according
to your system and operating system requirements.
Dev C++ [Link] Installation Guide
Installation Steps:
Step 1:
Double-click on the file devcpp_setup.exe and Click on the “Run” button.
Step 2:
Click on the “OK” button.
Step 3:
Click on the “OK” button.
Step 4:
Click on the “I Agree ” button.
Step 5:
Click on the “Next” button.
Step 6:
Click on the “Install” button.
Step 7:
Wait until the green bar completed
Step 8:
Click on the “Finish” button.
Your Dev C++ [Link] has been installed successfully. Now start writing
compiling and running programs and enjoy programming.
Dev C++ 5.9 Installation Guide
Installation Steps:
Step 1:
Double-click on the file devcpp_setup.exe and Click on the “Run” button.
Step 2:
Click on the “OK” button.
Step 3:
Click on the “OK” button.
Step 4:
Click on the “I Agree ” button.
Step 5:
Click on “Next” button.
Step 6:
Click on “Install” button.
Step 7:
Wait until the green bar completed
Step 8:
Click on “Finish” button.
Your Dev C++ [Link] has been installed successfully. Now start writing
compiling and running programs and enjoy programming.
Guidelines on how to use Dev-C++
Following are the steps to write, save, compile, and run a program, using
Dev-C++:
How to open Dev-C++:
Main interface of Dev-C++:
Write a new Program:
Where to write the code:
After writing your code:
Save the Program:
1st Step:
2nd Step:
How to compile the program:
1st Step:
2nd and 3rd step will be performed automatically
2nd Step:
3rd Step:
How to run the program:
Output will be displayed as:
Guidelines on how to use online C++ compiler
Following are the steps to write, compile, and run a program using an online
compiler:
Open a browser and type the following address in the address bar.
[Link]
Now, write the C++ code in the highlighted area.
Write your C++ code in the highlighted area.
After writing the code, click on the ‘Run’ button.
The output of the code will be shown in the highlighted area.
If the program contains syntax errors, then errors will be shown along with
the line number in the highlighted area.
After removing the syntax errors, click on the ‘Run’ button again to see the
output.
Lab 1-2: Object Orientation
Objective:
The objective of this lab is to teach students how to identify objects, their attributes and
behaviors from the real-world scenario.
Learning Outcomes:
After this lab, the students will be able to identify objects, attributes and behaviors from a given
scenario.
Problem Statement
Consider the following scenario and identify all objects, their attributes, and behaviors.
In the Virtual University bookshop, the handouts of all courses are provided at reasonable
prices. The handouts are made in accordance with the video lectures recorded by famous
professors. It is a step to facilitate students to easily digest the course contents.
You are required to extract the Class Name, attributes and behaviours (operations) from the
above scenario.
Class Name Attributes (characteristics) Behaviors (operations)
Solution:
Class Attributes (characteristics) Behaviors (operations)
Bookshop Name Set Order
Address (location) Get Order
Phone number Confirm Order
list of books Deliver order
Update Inventory (update order)
Payment receive/ collect
Handout Title Upload
No. of topics /chapters Download
Page number Edit
Author Print
Publisher Read
Creation date Write
Modify date Share
Edition View
Course Course code Add information
Course name View Information
Course instructor Edit information
Credit hour Read
Total marks Write
Grading scheme
No. of lectures
Video Video number View / watch
Lectures Name Record
Duration Upload
Video quality Download
Type Stop
Video URL Share
Pause
Forward
Reverse
Increase speed
Decrease speed
Increase volume
Decrease volume
playback
Professor Employee ID Teach
Name Develop assignment
Age Solve student’s problems
Gender Develop Quiz
Qualification Develop GDB
Specialization Prepare Exam
Designation Take Exam
Experience Invigilate
Salary Mark papers
No. of taught subjects Mark activities
Give grades
Prepare result
Student Student ID / Roll number Study
Name Give exam
Age Attempt activities
Gender Taking lectures
Student program Write notes
Semester Making time table
CGPA
No. of courses
Course No. of topics Upload
content Names Edit
Topic number View
Topic Description Share
Composed by Write
Publish by Download
Written by
Lab 2: Class Diagram
Objective:
The objective of this lab is to teach students how to identify classes and relationships between
classes and draw a UML class diagram by applying the concepts of inheritance, aggregation or
composition.
Learning Outcomes:
After this lab, the students will be able to draw a UML class diagram for a given scenario.
Problem Statement
Consider a scenario of an Employee Management System that is used to manage employee
records and departments. The system handles various types of employees and departments.
Employees in the organization can be of different types, such as Full-Time and Part-Time. Full-
time employees get a salary according to their designation whereas part-time employees get a
salary based on working hours. A Department contains multiple employees, but an employee is
associated with only one department at a time.
You are required to apply the concepts of inheritance, aggregation or composition to the given
scenario and draw a UML class diagram.
Solution:
Lab 3: Constructor overloading and copy constructor
Objective:
The objective of this lab is to teach students how to overload constructors, deep copy
constructors, and destructors in a class.
Learning Outcomes:
After this lab, the students will be able to overload constructors, copy constructors, and
destructors.
Problem Statement
Write a C++ program that consists of a class named Employee having the following data
members:
Employee id
Employee name
Employee salary
The class should have the following member functions:
Setters and getters functions
Default constructor
Parameterized constructor
Deep copy constructor
Destructor to deallocate the memory
Display () function
Within the main () function, create an object emp1 of class Employee and initialize its data
members using a parameterized constructor. Within the constructor, you have to call the setters
functions to set the values of these data members.
Now, create another object emp2 and initialize it with emp1 using the deep copy constructor.
After that, you have to call the display () function to show the data members of both objects.
Sample Output:
After running your program, the following screen should display.
Solution:
#include <iostream>
#include <string.h>
using namespace std;
class Employee
{
private:
int empId ;
char *empName ;
float empSalary ;
public:
void setId(int id){
empId = id ;
}
void setName(char *name){
empName = new char[strlen(name)+1];
strcpy(empName , name) ;
}
void setSalary( float salary){
empSalary = salary ;
}
int getId(){
return empId ;
}
const char *getName(){
return empName ;
}
float getSalary(){
return empSalary ;
}
// default construcor
Employee(){
empId = 0 ;
empName = NULL ;
empSalary = 0.0 ;
}
// parameterized construcor
Employee(int id, char *name, float salary){
setId(id);
setName(name);
setSalary(salary);
}
// copy constructor
Employee(const Employee & e){
empId = [Link] ;
empName = new char[strlen([Link])+1];
strcpy(empName , [Link]) ;
empSalary = [Link];
}
void display(){
cout << "Employee Id: " << getId() << endl ;
cout << "Employee Name: " << getName() << endl;
cout << "Employee Salary: " << getSalary() << endl << endl;
}
~Employee(){
delete []empName ;
}
};
int main()
{
Employee emp1 (10, "Ali", 50000);
Employee emp2 = emp1 ; // copy constructor will be called here
cout << "The data members of object 1:" << endl ;
[Link]();
cout << "The data members of object 2:" << endl ;
[Link]();
system("pause");
}
Lab 4: Constant and static members in classes
Objective:
The objective of this lab is to teach students how to define and use constant and static members
in classes.
Learning Outcomes:
After this lab, the students will be able to define and use constant and static members in
classes.
Problem Statement
Write a C++ program that creates a class named Employee having the following data members:
A static data member “count” to store the total number of Employee objects
Employee ID as a const data member
The class should contain the following member functions:
Constructor and destructor
Static member function to get the value of count
Const member function to get the value of employee ID
In the main () function, create three objects e1, e2, and e3 of type Employee and initialize the
value of employee id.
Also, create a constant object ‘e4’ of an Employee class and initialize the employee ID.
For each object, print the value of Employee ID using the const member function.
At the end of program, display the value of the “count” data member showing the total number
of employees.
Sample Output:
Following is a sample output for the above scenario:
Solution:
#include<iostream>
using namespace std;
class Employee
{
private:
const int empId ;
static int count;
public:
static int getCount(); // static function getCount() and its return type is int.
int getId() const ; // const function and its return type is int.
Employee(int); //Constructor
~Employee(); //Destructor
};
int Employee::count = 0;
int ::Employee::getCount() //definition of function getCount
{
return count;
}
int Employee::getId() const{ // definition of const member function
return empId ;
}
Employee::Employee(int id) :empId(id )//definition of constructor
{
count++;
}
Employee::~Employee() //definition of destructor
{
count--;
}
int main()
{
Employee e1(10);
cout << "Employee Id : " << [Link]() << endl ;
Employee e2(20);
cout << "Employee Id : " << [Link]() << endl ;
Employee e3(30);
cout << "Employee Id : " << [Link]() << endl ;
const Employee e4(40);
cout << "Employee Id : " << [Link]() << endl ;
//prints the number of total objects before deletion.
cout << endl << "Total Objects after creation : " << Employee::getCount() << endl <<
endl;
system("pause");
return 0 ;
}
Lab 5: Composition
Objective:
The objective of this lab is to teach students how to implement composition relationship
between classes using C++ code.
Learning Outcomes:
After this lab, the students can write C++ code for the composition relationships between
classes.
Problem Statement
Consider the following UML class diagram having composition relationships between classes
Customer and Account.
Customer class has the following data members:
Customer id
Customer name
Customer CNIC
Customer Address
Account
The class should have the following member functions:
Parameterized constructor
print()
withdraw()
deposit()
Destructor
Account class has the following data members:
Account No.
Balance
Bank name
Branch code
The class should have the following member functions:
Parameterized constructor
withdraw()
deposit()
print()
Destructor
You are required to implement the composition relationship between classes using C++ code.
Within the main () function, create an object of Customer class and initialize its data members
along with the Account details.
Now, call the deposit() function to deposit some amount then call the print () function which
will display all the values of Customer including their ID, name, CNIC, address and account
details.
Then, call the withdraw function to withdraw some amount and call the print () function which
will display all the values of Customer including their ID, name, CNIC, address and account
details.
Sample Output:
Following is a sample output for the above scenario:
Practice Questions:
Scenario 1
Suppose you are building a Sports Team management system. A team consists of multiple
players, but players can exist independently of Team.
The Player class has the following data members:
Player id
Player name
The class should have the following member functions:
Constructor
Destructor
showPlayer()
Team class has the following data members:
Team Id
Team name
Players
The class should have the following member functions:
Constructor
Destructor
addPlayers()
showPlayers()
You are required to implement the aggregation relationship between classes using C++ code.
Implement the main() function according to the functionalities given in the classes.
Scenario 2
Suppose you are building a Library management system. A Library consists of multiple books,
but books can exist independently of Library.
Book class has the following data members:
Book id
Book Title
Book Author
The class should have the following member functions:
Constructor
Destructor
print ()
Library class has the following data members:
Library Id
Library name
Books
The class should have the following member functions:
Constructor
Destructor
addBooks()
printBooks()
You are required to implement the aggregation relationship between classes using C++ code.
Implement the main() function according to the functionalities given in the classes.
Solution:
#include <iostream>
#include <string.h>
using namespace std;
class Account{
private:
int accNo ;
float balance ;
char *bankName ;
int branchCode ;
public:
Account(int no, float b, char *bName, int bCode){
accNo = no ;
balance = b ;
bankName = new char[strlen(bName)+1];
strcpy(bankName , bName) ;
branchCode = bCode ;
}
void deposit(float amount){
balance = balance+amount ;
}
void withdraw(float amount){
balance = balance-amount ;
}
void print(){
cout << "Account Number: " << accNo << endl ;
cout << "Bank Name: " << bankName<< endl;
cout << "Branch Code: " << branchCode << endl;
cout << "Balance: " << balance << endl << endl ;
}
~Account(){
delete []bankName;
}
};
class Customer
{
private:
int cusId ;
char *cusName;
char *cusCNIC;
char *cusAddress;
Account acc ;
public:
Customer(int id, char *name, char *cnic, char *address, int no, float b, char *bName, int
bCode) : acc(no, b, bName, bCode) {
cusId = id ;
cusName = new char[strlen(name)+1];
strcpy(cusName , name) ;
cusCNIC = new char[strlen(cnic)+1];
strcpy(cusCNIC , cnic) ;
cusAddress = new char[strlen(address)+1];
strcpy(cusAddress , address) ;
}
void deposit(float amount){
[Link](amount);
}
void withdraw(float amount){
[Link](amount);
}
void print(){
cout << "Customer Id: " << cusId << endl ;
cout << "Customer Name: " << cusName << endl;
cout << "Customer CNIC: " << cusCNIC << endl ;
cout << "Customer Address: " << cusAddress << endl ;
[Link]() ;
}
~Customer(){
delete []cusName ;
delete []cusCNIC ;
delete []cusAddress ;
}
};
int main()
{
Customer cus (10, "abc", "35204-7458545-9", "Lahore", 1, 50000, "HBL", 1924);
cout << "Customer infomration having initial amoount (50000) is given below:" << endl << endl ;
[Link]();
cout << "Customer information after depositing amount (10000) is given below:" << endl <<
endl ;
[Link](10000);
[Link]();
cout << "Customer inofmration after withdrawing amount (20000) is given below:" << endl <<
endl ;
[Link](20000);
[Link]();
system("pause");
return 0 ;
}
Lab 6: Operator Overloading
Objective:
The objective of this lab is to teach students how to overload some binary operators in
C++.
Learning Outcome:
After this lab, students will be able to overload +, -,*,/,+=,-=,*=,/= operators.
Problem Statement
Write a C++ program to perform the following tasks.
Create a class named Circle. Perform following tasks for this class.
a. Add one data member radius of type double.
b. Add setter and getter functions to set and get value of radius data member.
c. Create following objects: circle1, circle2, cricle3, circle4, circle5 and cricle6
of Circle class in main() function.
d. Set radius of circle1, circle2, and cricle3 to 6.3, 4.2, and 12.5 respectively.
e. Overload the + operator for the following types of operations.
i. circle4 = circle1 + circle2
ii. circle5 = circle2 + 8.23
iii. circle6 = 7.4 + circle2;
f. Display radius of circle4, circle5 and cricle6.
Sample Output:
After running your program, the following output should be displayed.
Practice Question:
Write C++ code to overload -, *, and / operators for the given class circle.
Solution:
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
void setRadius(double r) {
radius = r;
}
double getRadius( ){
return radius;
}
//Overloading of + operator to support operation: circle4 = circle1 + circle2
Circle operator + (const Circle& c) {
Circle temp;
[Link] = this->radius + [Link];
return temp;
}
//Overloading of + operator to support operation: circle2 + 8.23 (any double value)
Circle operator + (const double value) {
Circle temp;
[Link] = this->radius + value;
return temp;
}
//Overloading of + operator to support operation: 7.4 (any double value) + circle2;
friend Circle operator + (const double value, const Circle& c)
{
Circle temp;
[Link] = value + [Link];
return temp;
}
};
int main( ) {
Circle circle1, circle2, cricle3, circle4, circle5, circle6;
[Link](6.3);
[Link](4.2);
[Link](12.5);
circle4 = circle1 + circle2;// + circle3;
circle5 = circle2 + 8.23;
circle6 = 7.4 + circle2;
cout << "Radius of Circle 4 : " << [Link]() <<endl<<endl<<endl;
cout << "Radius of Circle 5 : " << [Link]() <<endl<<endl<<endl;
cout << "Radius of Circle 6 : " << [Link]() <<endl<<endl<<endl;
}
Lab 7: Overloading stream insertion, stream extraction and unary operators
Objective:
The objective of this lab is to teach students how to overload stream insertion, stream
extraction and unary operators in C++.
Learning Outcome:
After this lab, students will be able to overload stream insertion (<<), stream extraction
(>>) operators, unary minus (-), pre-increment, post-increment, pre-decrement and post-
decrement operators.
Problem Statement
A Complex number is represented as a sum of a real number and an imaginary number. Write a
C++ program that consists of a class named Complex which has data members real and imag.
Your task is to overload the following operators for the Complex class.
Stream insertion operator (<<)
Stream extraction operator (>>)
Unary minus operator (-)
Pre-increment operator (++)
Post-increment operator (++)
In the main () function, do the following.
Create an object com1 and take input using the stream extraction operator and print output using the
stream insertion operator.
Create an object com2 and print output of com2 object after executing the statement com2=-com1;
Create an object com3 and print output of com3 object after executing the statement com3=++com1;
Create an object com4 and print output of com4 object after executing the statement com4=com3++;
Sample Output:
Solution:
#include<iostream>
using namespace std;
class Complex
private:
int real, imag; //declaration of real and imaginary part of the complex number
public:
Complex(int r = 0, int i =0) //Parametrized Constructor
real = r; //assign the value
imag = i; //assign the value
//This function is automatically called when "<<" operator is used.
//prototype statement of stream insertion operator
friend ostream & operator << (ostream &outObj, const Complex &com);
//This function is automatically called when ">>" operator is used.
//prototype statement of stream extraction operator
friend istream & operator >> (istream &inObj, Complex &com);
Complex operator -( );
Complex operator ++();
Complex operator ++(int);
};
ostream & operator << (ostream &outObj, const Complex &com)
//this is the code to print the real and imaginary values of complex number
outObj << "("<<[Link]<<")";
outObj << "+" << "("<< [Link] << "i" << ")"<<endl;
return outObj;
istream & operator >> (istream &inObj, Complex &com)
//this is the code to read the real and imaginary values of complex number
cout << "Please enter real part of complex number: ";
inObj >> [Link];
cout << "Please enter imaginary part of complex number: ";
inObj >> [Link];
return inObj;
}
Complex Complex::operator -()
Complex temp;
[Link] = -real;
[Link] = -imag;
return temp;
Complex Complex::operator ++()
real = real + 1;
return * this;
Complex Complex::operator ++(int)
Complex temp=*this;
real = real + 1;
return temp;
int main()
Complex com1; //Creation of object of class Complex
cin >> com1; //This will call the insertion operator function
cout << "The Complex object com1 is: ";
cout << com1; //This will call the extraction operator function
Complex com2=-com1;
cout << "The Complex object com2 is: ";
cout<<com2;
Complex com3=++com1;
cout << "The Complex object com3 is: ";
cout<<com3;
Complex com4=com3++;
cout << "The Complex object com4 is: ";
cout<<com4;
return 0;
}
Lab 8: Inheritance
Objective:
The objective of this lab is to teach students how to implement
inheritance in C++.
Learning Outcome:
After this lab, students will be able to implement inheritance.
Problem Statement
Write a C++ Program to create a base class Employee that stores the
employee's name and ID. Derive a class Engineer from Employee that adds
the following additional attributes:
specialization (e.g., Software, Civil, Electrical)
experience (in years)
projectName (name of the current project)
The program should input and display all details of an engineer using
appropriate methods. This program should demonstrate how data and
behavior from the base class are inherited and extended in the derived class.
Sample Output
After running your program, the following output screen should display.
Practice Questions:
Practice Question 1:
Write a C++ program for the following:
Create a base class Book with data members: title and author. Derive a class
EBook that adds fileSize (in MB) and format (e.g., PDF, EPUB). Your program
should input and display all details of an EBook.
Practice Question 2:
Write a C++ program for the following:
Create a base class User with attributes username and email. It should
include getter and setter functions. Derive two classes:
Admin, which adds a method accessControlPanel()
Member, which adds a method browseContent()
In main() function, create objects of both derived classes. The program
should input and display the username and email using inherited methods,
and then call the respective methods of the Admin and Member classes to
display their specific functionalities.
Solution:
#include <iostream>
using namespace std;
// Base class
class Employee {
protected:
string name;
int id;
public:
void getEmployeeDetails() {
cout << "Enter Employee Name: ";
getline(cin, name);
cout << "Enter Employee ID: ";
cin >> id;
[Link](); // Clear buffer
void displayEmployeeDetails() {
cout << "\nEmployee Name: " << name << endl;
cout << "Employee ID: " << id << endl;
};
// Derived class
class Engineer : public Employee {
private:
string specialization;
int experience; // years of experience
string projectName; // current project
public:
void getEngineerDetails() {
getEmployeeDetails(); // base class method
cout << "Enter Specialization: ";
getline(cin, specialization);
cout << "Enter Years of Experience: ";
cin >> experience;
[Link]();
cout << "Enter Project Name: ";
getline(cin, projectName);
void displayEngineerDetails() {
displayEmployeeDetails(); // base class method
cout << "Specialization: " << specialization << endl;
cout << "Experience: " << experience << " years" << endl;
cout << "Project Name: " << projectName << endl;
};
// Main function
int main() {
Engineer eng;
[Link]();
cout<<endl<<"Displaying Engineer Information..."<<endl;
[Link]();
return 0;
}
Lab 09:
Objective:
Understand and apply public, private, and protected inheritance in C++
Observe how access specifiers affect inherited members.
Learn how base class behavior is inherited, hidden, or overridden.
Learning Outcome:
After completing this lab, students will be able to identify and understand the
accessibility of base class data members across different types of inheritance.
Problem Statement
Write a C++ program which should consist of following four classes.
1. Base
2. Derived_Private
3. Derived_Protected
4. Derived_Public
“Base” class should consist of following data members along with following type.
Data member Access Specifier
secret private
protect protected
access public
Further, “Base” class should contain default constructor to initialize its data members.
Other three classes should be inherited from “Base” class with respect to following type of
inheritance.
Class Inheritance type
Derived_Private Private
Derived_Protected Protected
Derived_Public Public
All three derived classes should contain show() function, which should display the values of
secret, protect and access data member of base class. On running this program, your compiler
will generate compile time errors. Carefully observe for which type of base class data member,
compiler is generating error.
Class Diagram
Compilation Results
Practice Question:
Develop a simple vehicle management system in C++ using different types of inheritance:
public, private, and protected.
Tasks to do:
1. Create the Vehicle class
o Include a protected int speed and a public method drive() that prints the
speed.
2. Create the Car class
o Inherit from Vehicle using public inheritance
o Add a numberOfDoors member
o Add a public method showDetails() that prints speed and
numberOfDoors.
3. Create the SportsCar class
o Inherit from Car using private inheritance
o Add a public method enableTurbo() that prints "Turbo enabled!"
o Use drive() inside enableTurbo() if needed
4. Create the ElectricCar class
o Inherit from Car using protected inheritance
o Add a batteryLevel member
o Override the drive() method to display "Driving electric car at X km/h with
Y% battery"
5. In your main() function, do the following:
o Create objects of Car, SportsCar, and ElectricCar
o Try calling:
drive() on each object
showDetails() on each object
enableTurbo() on the SportsCar
o Observe which calls are allowed and which are restricted.
6. After implementing the scenario, find answers of following questions:
o Which members were accessible in main() and which were not?
o Why was drive() accessible in some cases and not others?
o What’s the effect of private and protected inheritance on base class
methods?
Solution:
#include<iostream>
using namespace std;
class Base
{
private:
int secret; //Declaration of variable “secret” that is private.
protected:
int protect; //Declaration of variable “protect” that is protected.
public:
int access; //Declaration of variable “access” that is public.
Base() //Constructor of base class.
{
//Assignment of default value to variables.
access=0;
protect=0;
secret=0;
};
//private inheritance between Base(parent) and Derived_Private(child) class. It makes the public and protected
//members of the base class private in the derived class.
class Derived_Private: private Base
public:
void show() //show function to display the values of variable.
cout<<access<<endl;
cout<<protect;
cout<<secret;
};
//protected inheritance between Base(parent) and Derived_Protected(child) class. It makes the public and
//protected members of the base class protected in the derived class.
class Derived_Protected: protected Base
public:
void show() //show function to display the values of variable.
cout<<access;
cout<<protect;
cout<<secret;
};
//protected inheritance between Base(parent) and Derived_Public(child) class. It makes public members of the
//base class public in the derived class, and the protected members of the base class remain protected in the
//derived class.
class Derived_Public: public Base
public:
void show() //show function to display the values of variable.
cout<<access;
cout<<secret;
cout<<protect;
};
int main()
Derived_Public child1; //Object of Derived class
cout<<"This is accessibility of base data members in derived class in case of public
inheritance"<<endl;
[Link](); //call the show function
Derived_Protected child2; //Object of Derived class
cout<<"This is accessibility of base data members in derived class in case of protected
inheritance"<<endl;
[Link](); //call the show function
Derived_Private child3; //Object of Derived class
cout<<"This is accessibility of base data members in derived class in case of private
inheritance"<<endl;
[Link](); //call the show function
}
Lab 10: Polymorphism
Objective:
The objective of this lab is to teach students how to implement Polymorphism in C++.
Understand runtime polymorphism using virtual functions
Practice function overriding in derived classes
Use base class pointers or references to achieve polymorphic behavior
Learning Outcome:
After this lab, students will be able to implement polymorphism.
Problem Statement
Design a payroll system for a company with different types of employees. The goal is to use
polymorphism to calculate salaries for various employee roles, where each type has a different
way of computing pay.
Tasks to do:
Create following classes with given data members and member functions/methods.
1. Employee (Base Class)
Protected member: name
Public virtual method: calculateSalary()
Public method: displayInfo() that displays the employee name
Constructor: Accepts a name and initializes the name member.
Destructor: Declare as virtual to allow safe polymorphic deletion. Display message as per
sample output.
2. FullTimeEmployee (Derived Class)
Inherits from: Employee
Additional members: basicSalary, allowance
Overrides: calculateSalary() to return basicSalary + allowance
Constructor: Accepts name, basicSalary, and allowance. Calls base class constructor to
initialize name.
Destructor: Display message as per sample output.
3. PartTimeEmployee (Derived Class)
Inherits from: Employee
Additional members: hoursWorked, hourlyRate
Overrides: calculateSalary() to return hoursWorked * hourlyRate
Constructor: Accepts name, hoursWorked, and hourlyRate. Calls base class constructor.
Destructor: Display message as per sample output.
4. ContractEmployee (Derived Class)
Inherits from: Employee
Member: contractAmount
Overrides: calculateSalary() to return contractAmount
Constructor: Accepts name and contractAmount. Calls base class constructor.
Destructor: Display message as per sample output.
In your main() function:
o Create an array or vector of Employee* or Employee& pointing to objects of
each derived class.
o Call displayInfo() and calculateSalary() polymorphically
o Print the salaries using only base class pointers
Sample Output
Practice Question:
Develop a notification system that can send alerts via different channels like email, SMS, and
push notifications. Each notification type behaves differently when sending a message. The
system must handle all notifications using polymorphism to treat them generically.
Tasks to Do:
Create following classes with given data members and member functions/methods.
1. Notification (Base Class)
o protected member: recipient
o public virtual method: send()
o public method: setRecipient() and getRecipient()
2. EmailNotification (Derived Class)
o Inherits from Notification
o Overrides send() to print: "Sending Email to [recipient]"
3. SMSNotification (Derived Class)
o Inherits from Notification
o Overrides send() to print: "Sending SMS to [recipient]"
4. PushNotification (Derived Class)
o Inherits from Notification
o Overrides send() to print: "Sending Push Notification to [recipient]"
In your main() function:
o Create an array or vector of Notification* pointing to objects of each derived
class
o Set a recipient for each notification using setRecipient()
o Loop through the collection and call send() polymorphically
Observation:
Remove the virtual keyword from the base class method and observe the effect on output.
Solution:
#include <iostream>
using namespace std;
// 1. Base Class
class Employee {
protected:
string name;
public:
Employee(string n) : name(n) {
virtual double calculateSalary() {
return 0.0;
void displayInfo() {
cout << "Employee Name: " << name << endl;
virtual ~Employee() {
cout << "Employee destructor called for " << name << endl;
};
// 2. FullTimeEmployee Class
class FullTimeEmployee : public Employee {
private:
double basicSalary;
double allowance;
public:
FullTimeEmployee(string n, double basic, double allow)
: Employee(n), basicSalary(basic), allowance(allow) {
double calculateSalary() override {
return basicSalary + allowance;
}
~FullTimeEmployee() {
cout << "FullTimeEmployee destructor called for " << name << endl;
};
// 3. PartTimeEmployee Class
class PartTimeEmployee : public Employee {
private:
int hoursWorked;
double hourlyRate;
public:
PartTimeEmployee(string n, int hours, double rate)
: Employee(n), hoursWorked(hours), hourlyRate(rate) {
double calculateSalary() override {
return hoursWorked * hourlyRate;
~PartTimeEmployee() {
cout << "PartTimeEmployee destructor called for " << name << endl;
}
};
// 4. ContractEmployee Class
class ContractEmployee : public Employee {
private:
double contractAmount;
public:
ContractEmployee(string n, double amount)
: Employee(n), contractAmount(amount) {
double calculateSalary() override {
return contractAmount;
~ContractEmployee() {
cout << "ContractEmployee destructor called for " << name << endl;
};
// 5. Main Function (Using array of pointers)
int main() {
Employee* employees[3];
employees[0] = new FullTimeEmployee("Nadia", 50000, 10000);
employees[1] = new PartTimeEmployee("Jamil", 120, 50);
employees[2] = new ContractEmployee("Ali", 45000);
cout << "\n=== Payroll Report ===\n";
for (int i = 0; i < 3; ++i) {
employees[i]->displayInfo();
cout << "Salary: " << employees[i]->calculateSalary() << "\n\n";
// Deleting objects to trigger destructors
for (int i = 0; i < 3; ++i) {
delete employees[i];
return 0;