0% found this document useful (0 votes)
12 views73 pages

Dev-C++ Installation and Usage Guide

This document outlines a series of labs aimed at teaching students various programming concepts in C++, including installation of Dev-C++, object orientation, UML class diagrams, constructor overloading, and composition. Each lab has specific objectives, learning outcomes, and problem statements that guide students through practical coding exercises. The document also includes sample codes and expected outputs for better understanding.

Uploaded by

bc240412496mmu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views73 pages

Dev-C++ Installation and Usage Guide

This document outlines a series of labs aimed at teaching students various programming concepts in C++, including installation of Dev-C++, object orientation, UML class diagrams, constructor overloading, and composition. Each lab has specific objectives, learning outcomes, and problem statements that guide students through practical coding exercises. The document also includes sample codes and expected outputs for better understanding.

Uploaded by

bc240412496mmu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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;

Common questions

Powered by AI

Destructors are essential in classes that handle dynamic memory allocation to ensure that memory is released when an object is destroyed, preventing memory leaks. In the Employee and Customer classes, destructors explicitly invoke the delete operator to release memory allocated with new for dynamically set string attributes like empName and cusName . Without proper destructors, each time an object goes out of scope, memory would remain allocated unnecessarily, which can lead to memory exhaustion and inefficient memory use over prolonged application execution.

The deep copy constructor in the Employee class performs a deep copy of the dynamically allocated memory for the empName attribute, ensuring that a new memory location is allocated for the string and its value is copied over from the source object. This is necessary to avoid the issue of both the source and the copy pointing to the same memory location, which would lead to data corruption or crashes when one of the objects is destroyed and attempts to free the same memory location .

Friend functions in operator overloading allow for more flexible expression syntax by enabling non-member functions to access private or protected data members of a class. In the Circle class, the friend function for operator+ caters to the addition of a double value with a Circle object in both orders (i.e., circle + value and value + circle). This extends usability beyond the limitations of member functions, allowing expressions that resemble basic arithmetic operations, thus mimicking native type operations, and making code involving user-defined types more intuitive and readable.

The Engineer class extends the Employee class by adding additional attributes such as specialization, experience, and projectName. Additionally, specific methods for inputting and displaying these attributes collectively demonstrate class extension, combining inherited behaviors from the Employee class with new functionalities specific to engineers . This illustrates the concept of extending base class data and methods to support specialized applications in derived classes, integrating new domain-specific characteristics.

Composition represents a 'has-a' relationship where one class contains objects of another class as member variables. In the provided code, the Customer class contains an object of the Account class as a private member, establishing a composition relationship . This allows the Customer class to use the Account class's methods and properties, integrating the two classes' functionalities as needed.

Private inheritance in C++ means that public and protected members of the base class become private members of the derived class. This affects access as the derived class cannot use these base class members publicly or allow outside classes access. Within the derived class, only private members of the base can be accessed, and functionality must be managed internally without exposing the interface. This encapsulates the base class's data more strictly compared to public or protected inheritance, limiting inheritance visibility to only within the derived class .

Static data members are shared among all objects of a class, and they maintain a single location in memory regardless of the number of instances created. In the Employee class, the static data member 'count' is used to track the total number of Employee objects by being incremented in the constructor and decremented in the destructor . This demonstrates how class-level data can be maintained without associating it with any specific object instance.

Getters and setters are used to encapsulate class data members by providing controlled access and modifications. This promotes data integrity by validating data through setters before updating class attributes. In the Employee class, setters like setId ensure correct data types and values are assigned, while getters like getId provide read-only access to private data . This approach prevents unauthorized access or modification, maintaining object stability and correctness. Challenges can include ensuring all validation is managed correctly, which getters and setters help by centralizing control.

The operator overloading for the + operator in the Circle class is defined to handle both adding two Circle objects and adding a Circle object with a double value. For Circle objects, the operator+ overloads by creating a new Circle with the sum of the radii of the two Circle objects . When adding a double value, the operator+ takes either a Circle object on the left and a double on the right or a double on the left and a Circle on the right, adjusting the radius of the resulting Circle by the specified double value . This demonstrates polymorphic behavior where the operator adapts its functionality based on input types.

Overloading the stream insertion and extraction operators in the Complex class allows objects of the class to be directly used with input/output streams in a convenient way. The << operator is overloaded to customize how Complex objects are formatted when output to a stream, which aids in displaying the object's state meaningfully . Similarly, the >> operator is overloaded to facilitate the reading of Complex object data directly from input streams, standardizing the process of populating object fields which enhances usability and consistency in stream-based processing .

You might also like