0% found this document useful (0 votes)
23 views

Lab Solution

The document outlines a series of labs for a C++ course, detailing objectives, learning outcomes, and specific tasks for each lab. Labs cover topics such as installation of Dev-C++, object orientation, class diagrams, constructor overloading, constant and static members, composition, and operator overloading. Each lab includes problem statements, guidelines, and sample code to help students understand and apply the concepts taught.

Uploaded by

goleme8735
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Lab Solution

The document outlines a series of labs for a C++ course, detailing objectives, learning outcomes, and specific tasks for each lab. Labs cover topics such as installation of Dev-C++, object orientation, class diagrams, constructor overloading, constant and static members, composition, and operator overloading. Each lab includes problem statements, guidelines, and sample code to help students understand and apply the concepts taught.

Uploaded by

goleme8735
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 80

CS304p – ALL Labs

Mark Maverick
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++ 4.9.9.2 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++ 4.9.9.2 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++ 4.9.9.2 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.

https://www.programiz.com/cpp-programming/online-compiler/

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 Attributes Behaviors (operations)


Name (characteristics)

Solution:

Class Attributes Behaviors (operations)


(characteristics)
Booksho Name Set Order
p 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 Study
number Give exam
Name Attempt activities
Age Taking lectures
Gender Write notes
Student program Making time table
Semester
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;
}
Employee(){
empId = 0;
empName = NULL;
empSalary = 0.0;
}
Employee(int id, char *name, float salary){
setId(id);
setName(name);
setSalary(salary);
}

Employee(const Employee &obj){


empId = obj.empId;
empName = new char[strlen(obj.empName)+1];
strcpy(empName, obj.empName);
empSalary = obj.empSalary;
}

void Display(){
cout << "Employee ID: " << getId() << endl;
cout << "Employee Name" << getName() << endl;
cout << "Employee Salary" << getSalary() << endl;
}
~Employee(){
delete[]empName;
}
};
int main(){
Employee emp1(100, "Mark", 50000);
Employee emp2 = emp1; // Copy constructor called
cout << "The Data Members of Object 01:" << endl;
emp1.Display();
cout << "The Data Members of Object 02:" << endl;
emp2.Display();
return 0;
}

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:
static int count;
const int empId;
public:
static int getCount(){
return count;
}
int getId() const{
return empId;
}
Employee(): empId(0){}
Employee(int id): empId(id){
count++;
}
~Employee(){
count--;
}
};
int Employee::count = 0;

int main(){
Employee e1(10);
cout << "Employee Id: " << e1.getId() << endl;
Employee e2(20);
cout << "Employee Id: " << e2.getId() << endl;
Employee e3(30);
cout << "Employee Id: " << e3.getId() << endl;
const Employee e4(40);
cout << "Employee Id: " << e4.getId() << endl;
cout << "Totoal Objects After Creation: " << Employee::getCount()
<< endl;
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:


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)
{
acc.deposit(amount);
}

void withdraw(float amount)


{
acc.withdraw(amount);
}
void print()
{
cout << "Customer Id: " << cusId << endl;
cout << "Customer Name: " << cusName << endl;
cout << "Customer CNIC: " << cusCNIC << endl;
cout << "Customer Address: " << cusAddress << endl;
acc.print();
}

~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;
cus.print();
cout << "Customer information after depositing amount (10000) is
given below:" << endl
<< endl;
cus.deposit(10000);
cus.print();
cout << "Customer inofmration after withdrawing amount (20000) is
given below:" << endl
<< endl;
cus.withdraw(20000);
cus.print();
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;
temp.radius = this->radius + c.radius;
return temp;
}
//Overloading of + operator to support operation: circle2 + 8.23 (any
double value)
Circle operator + (const double value) {
Circle temp;
temp.radius = 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;
temp.radius = value + c.radius;
return temp;
}
};

int main( ) {
Circle circle1, circle2, cricle3, circle4, circle5, circle6;
circle1.setRadius(6.3);
circle2.setRadius(4.2);
cricle3.setRadius(12.5);
circle4 = circle1 + circle2;// + circle3;
circle5 = circle2 + 8.23;
circle6 = 7.4 + circle2;
cout << "Radius of Circle 4 : " << circle4.getRadius()
<<endl<<endl<<endl;
cout << "Radius of Circle 5 : " << circle5.getRadius()
<<endl<<endl<<endl;
cout << "Radius of Circle 6 : " << circle6.getRadius()
<<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 << "("<<com.real<<")";
outObj << "+" << "("<< com.imag << "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 >> com.real;
cout << "Please enter imaginary part of complex number: ";
inObj >> com.imag;
return inObj;
}
Complex Complex::operator -()
{
Complex temp;
temp.real = -real;
temp.imag = -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 that consists of a class named Planet which has no
data member and only contains a default constructor. Your program
should contain two more classes Inner_Planet and Outer_Planet. Both
of these classes should also contain a default constructor. Your program
should implement the concept of inheritance between “Planet class,
Inner_Planet class, and Outer_Planet class”.

Sample Output

After running your program, the following output screen should display.
Solution:

#include<iostream>
#include<conio.h>
using namespace std;
class Planet
{
public:
Planet() //Default constructor of parent class Planet
{
cout<<"Planet Constructor is called"<<endl;
}
};

class Inner_Planet: Planet //Inheritance between Planet(parent)


and Inner_Planet(child)
{
public:
Inner_Planet() //Default constructor of child class
Inner_Planet
{
cout<<"Inner Planet Constructor is called"<<endl;
}
};

class Outer_Planet: Planet //Inheritance between Planet(parent)


and Outer_Planet(child)
{
public:
Outer_Planet() //Default constructor of child class
Outer_Planet
{
cout<<"Outer Planet Constructor is called"<<endl;
}
};
main()
{
Inner_Planet IP;
//Object of child class Inner_Planet. It will print the default
constructor of parent and then child class.
cout<<"\n";
Outer_Planet OP; //Object of child class Outer_Planet. It
will print the default constructor of parent and then child class.

cout<<"\n";
system("pause");
}
Lab 09:

Objective:

 The objective of this lab is to teach students how to implement


various types of inheritance (public, private, and protected) in C++.
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

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;
child1.show(); //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;
child2.show(); //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;
child3.show(); //call the show function
return 0;
}
Lab 10: Polymorphism

Objective:

 The objective of this lab is to teach students how to implement


Polymorphism in C++.
Learning Outcome:

 After this lab, students will be able to implement polymorphism.

Problem Statement

Consider the given class diagram and perform the tasks given below.

Part (1):

Write C++ program which should contain three classes as follows:

 PlainBox
 LunchBox
 GiftBox
“LunchBox” and “GiftBox” classes should be publicly inherited from
PlainBox Class.

All three classes should contain Display() function, which should display
respective class name.

In main() function, create objects of LunchBox and GiftBox classes


dynamically. Static type of these objects should be “PlainBox”. Using
object of PlainBox, call Display() function.

Following is a sample output for the above scenario:

Sample Output
Solution:

Solution

#include<iostream>
using namespace std;
class plainBox //Base Class
{
public:
void display() //Display Function to display “Plain Box Class”.
{
cout<<"Plain Box Class"<<endl;
}
};

class LunchBox: public plainBox //LunchBox(child) class is inherited


from the PlainBox(parent) class.
{
public:
void display() //Display Function to display “Lunch Box Class”.
{
cout<<"Lunch Box Class"<<endl;
}
};
class GiftBox: public plainBox //GiftBox(child) class is inherited
from the PlainBox(parent) class.
{
public:
void display() //Display Function to display “Gift Box Class”.
{
cout<<"Gift Box Called"<<endl;
}
};
int main()
{
plainBox *LB= new LunchBox();
//This statement is creating an object dynamically and binds its
address to a pointer.
//This is the declaration of variable named LB which is a pointer to a
plainBox. This pointer object has automatic storage duration. It is
then initialized with the result of new LunchBox(). This new keyword
creates an LB object with dynamic storage duration and then returns a
pointer to it.
LB->display();
//Calling Display Function.
plainBox *GB= new GiftBox();
//This statement is creating an object dynamically and binds its
address to a pointer.
//This is the declaration of variable named GB which is a pointer to a
plainBox. This pointer object has automatic storage duration. It is
then initialized with the result of new GiftBox(). This new keyword
creates an GB object with dynamic storage duration and then returns a
pointer to it.
GB->display();
//Calling Display Function.
system("pause");
return 0;
}

Part (2):

Make Display() function of “PlainBox” class virtual and then run the
program. Your output should be as follows:

Sample Output

Solution:
#include<iostream>
using namespace std;
class plainBox //Base Class
{
public:
virtual void display()
//A virtual function is a member function within the base class that we
redefine in a derived class. It is //declared using the virtual
keyword. When a class containing virtual function is inherited, the
derived //class redefines the virtual function to suit its own needs.
{
cout<<"Plain Box Class"<<endl; //Display Function to display
“Plain Box Class”.
}
};
class LunchBox: public plainBox //LunchBox(child) class is inherited
from the PlainBox(parent) class.
{
public:
void display()
{
cout<<"Lunch Box Class"<<endl; //Display Function to display
“Lunch Box Class”.
}
};
class GiftBox: public plainBox //GiftBox(child) class is inherited
from the PlainBox(parent) class.
{
public:
void display()
{
cout<<"Gift Box Called"<<endl; //Display Function to display
“Gift Box Class”.
}
};
int main()
{
plainBox *LB= new LunchBox();
//This statement is creating an object dynamically and binds its
address to a pointer.
//This is the declaration of variable named LB which is a pointer to a
plainBox. This pointer object has automatic storage duration. It is
then initialized with the result of new LunchBox(). This new keyword
creates an LB object with dynamic storage duration and then returns a
pointer to it.
LB->display(); //Calling Display Function.
plainBox *GB= new GiftBox();
//This statement is creating an object dynamically and binds its
address to a pointer.
//This is the declaration of variable named GB which is a pointer to a
plainBox. This pointer object has automatic storage duration. It is
then initialized with the result of new GiftBox(). This new keyword
creates an GB object with dynamic storage duration and then returns a
pointer to it.
GB->display(); //Calling Display Function.
system("pause");
return 0;
}

Lab 11: Function Templates


Covering Lectures: 32 - 33

Objective:

This Lab aims to give students a deep understanding of Functions and


Class templates.

Learning Outcomes:

After completing this lab, students can practice generic programming in


their programs.

Problem Statement:

Write C++ code for a class Temp. The Class does not have any data
member but a member function “Compare()”. The function accepts two
values either integer, double, characters, or strings, and compares them.
The function returns true if the two passed values are equal otherwise
returns false.

Sample Output:

Practice Questions:

 Write a C++ code for swapping the data of two variables. The
variables can be of any type (int, float, char etc.) using the function
templates.
 Write a C++ Program to find the Sum of an Array using a class
template. The array elements can be int, float, and double types.
Character type data is not allowed.
 Write a C++ Program to find the Square of a number using a single
template class. The number can be an integer, float, or double data
type.
Solution:

#include<iostream>
#include<string>
using namespace std;
class temp
{
public:
template <typename T> //Template
bool compare(T first, T second) //Function to compare two
values of any type.
{
if(first==second) //if the first value is equal to second
value
{
return true; //Then it return the true
}
else
{
return false; //if values are not equal it returns
false
}
}
};
int main()
{
temp t1,t2,t3,t4; //Object creation of type temp
bool r1,r2,r3,r4;
int a=10, b=20; //variables of integer type.
cout<<endl<<"Passing Integer to Function"<<endl;
r1=t1.compare(a,b); //Calling the compare function with two
integer variables.
if(r1==true) //if the function returns true it will print the
given cout statement.
{
cout<<a<<" and "<<b<<" are equal"<<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<a<<" and "<<b<<" are not equal" <<endl;
}
float c=10.0, d=30.9; //variables of Float type.
cout<<endl<<"Passing floats to Function"<<endl;
r3=t3.compare(c, d); //Calling the compare function with two float
variables.
if(r3==true) //if the function returns true it will print the given
cout statement.
{
cout<<c<<" and "<<d<<" are equal"<<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<c<<" and "<<d<<" are not equal"<<endl;
}
//variables of string type.
string str1="Pakistan";
string str2="Pakistan";
cout<<endl<<"Passing strings to Function"<<endl;
r2=t2.compare(str1, str2); //Calling the compare function with two
string variables.
if(r2==true) //if the function returns true it will print the
given cout statement.
{
cout<<str1<<" and "<<str2<<" are equal" <<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<str1<<" and "<<str2<<" are not equal" <<endl;
}

string str3="Hello";
string str4="hello";
cout<<endl<<"Passing strings with case sensitivity to
Function"<<endl;
r4=t4.compare(str3, str4); //Calling the compare function with two
string variables.
if(r4==true) //if the function returns true it will print the
given cout statement.
{
cout<<str3<<" and "<<str4<<" are equal" <<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<str3<<" and "<<str4<<" are not equal" <<endl;
}
system("pause");
return 0;
}
Lab 12: Class Templates, General, Partial, and Complete
Specialization

Covering Lectures: 34 - 36

Objective:

This Lab aims to give students a deep understanding of General, Partial,


and Complete Specialization concepts.

Learning Outcomes:

After completing this lab, students can practice General, Partial, and
Complete Specialization in programs.

Part a.

Problem Statement:

Write a C++ code for a generic class “Container” that stores two values of
potentially different types. The goal is to demonstrate:

 Complete Specialization for Container when both values are bool.


This specialization should handle Boolean-specific logic, such as
counting how many true values are stored.
 Partial Specialization for Container when one value is always an
integer. This should enable additional operations, like comparing the
two values.
Tasks:

Implement the following:

 A general Container class template that stores two values of types


T1 and T2.
 A complete specialization for Container<bool, bool> that adds a
function countTrue() to count the number of true values stored.
 A partial specialization for Container<int, T> (when one value is
always of the type int and the second value can be of any data
type), which adds a method isEqual() to check if the two values are
equal or not.
 All classes should have print() function to display the values of the
variables on the screen.
 Write a main() function to demonstrate the general template, partial
specialization, and complete specialization according to the sample
output as given below.
Sample Output:
Practice Questions:

 Write a C++ program to manage different types of delivery vehicles.


You have to write
o A generic template for deliveryvehicles with two values of
types “VehcileType” and “FuelType” and a print () function.
The print () function will display the line “General Delivery
Vehicle”, the name, and the fuel type of the vehicle.
o You want to handle trucks differently from other vehicles so
write a specialized deliveryvehicles class for Trucks and
FuelType and a print () Function. The print () function will
display the line “Truck Delivery Vehicle”, the name, and the
fuel type of the vehicle.
o You want to handle electric bicycles in a completely
specialized way, as they are a special case compared to other
vehicles.

Solution:

#include<iostream>
#include<typeinfo>
using namespace std;

// General template for Container


template <typename T1, typename T2>
class Container {
public:
T1 first;
T2 second;

Container(T1 a, T2 b) : first(a), second(b) {}


void print() const {
cout << "First: " << first << ", Second: " << second << endl;
}
};

// Partial specialization when both types are the same


template <typename T>
class Container<int, T> {
public:
int first;
T second;

Container(int a, T b) : first(a), second(b) {}

void print() const {


cout << "First number is of Type: " << typeid(int).name() <<
", Second number is of Type: " << typeid(T).name() << ": First = " <<
first << ", Second = " << second << endl;
}

bool isEqual() const {


return first == second;
}
};

// Complete specialization for Container<bool, bool>


template <>
class Container<bool, bool> {
public:
bool first;
bool second;

Container(bool a, bool b) : first(a), second(b) {}

void print() const {


cout << "Boolean Container: First = " << (first ? "true" :
"false")
<< ", Second = " << (second ? "true" : "false") << endl;
}

int countTrue() const {


return (first ? 1 : 0) + (second ? 1 : 0);
}
};

// Main function to demonstrate usage


int main() {
// General container with two different types
cout<<endl<<"***General Template***"<<endl;
Container<float, int> generalContainer(3.14, 42);
generalContainer.print();

// Partial specialization with same types


cout<<endl<<"***Partial Specilialization When First Value is of
Type Integer and Second Value is of Type Float***"<<endl;
Container<int, float> DiffContainer(5, 4.5);
DiffContainer.print();
cout << "Are the two values equal? " << (DiffContainer.isEqual() ?
"Yes" : "No") << endl;

cout<<endl<<"***Partial Specilialization When Both Values are of


Type Integer***"<<endl;
Container<int, int> intContainer(5, 5);
intContainer.print();
cout << "Are the two values equal? " << (intContainer.isEqual() ?
"Yes" : "No") << endl;

// Complete specialization for bool


cout<<endl<<"***Complete Specilialization When First value is True
and Second is False***"<<endl;
Container<bool, bool> boolContainer(true, false);
boolContainer.print();
cout << "Number of true values: " << boolContainer.countTrue() <<
endl;

cout<<endl<<"***Complete Specilialization When First value od True


and Second is True***"<<endl;
Container<bool, bool> bool1Container(true, true);
bool1Container.print();
cout << "Number of true values: " << bool1Container.countTrue() <<
endl;

return 0;
}
Lab 13: Templates, Inheritance, Friends

Covering Lectures: Lectures 37 - 38

Objective:

This Lab aims to give students a deep understanding of the basic use of

 Templates and Inheritance in C++


 Templates and Friends in C++
Learning Outcomes:

After completing this lab, students can practice different types of


templates with the inheritance and Friends.

Part a.

Problem Statement:

Write a C++ code for a template-based class Shape with two derived
classes Rectangle and Circle. Derived classes are also template classes.

 Define a base class Shape with a pure virtual function getArea() to


calculate the area.
 Define two derived classes:

o Rectangle that calculates the area of a rectangle (length *


width).
o Circle that calculates the area of a circle (π * radius^2).

 Write a main function that:

o Creates two instances of Rectangle class with double and


integer datatypes.
o Creates two instances of Circle class with double and integer
datatypes.
o Call the getArea() function with all the instances of both
classes as per the sample output.

Sample Output:
Part b.

Problem Statement:

Write C++ code for the following template readData and Subtract classes.

Subtract class is the friend of the ReadData class and can access the
private data members of the Subtract class.

The read() method of the Subtract class takes input from the user for both
data members.

In the Subt() function create two objects of ReadData for int and float,
perform subtraction on the data for both objects, and print the result for
each datatype.

Sample Output:
Practice Questions:

 Question 1: Write a C++ code

o for a non-template class Color with data member mcolor and


getter() and setter() functions. The setter() function will set
the mcolor value. The getter() function will return the name of
the color.
o For a template class Circle inherited from the class Color. The
Circle class has data member radius.
o In the mian () function create the objects of class Cirle for int
and double datatypes and set the values of radius and color.
Display the values of both variables using the Circle class
objects.

 Question 2: You are working on a banking system that manages


various bank accounts (e.g., savings, checking, etc.). Create a
template class Account<T> to store account details, where T can
represent different currencies (like USD, EUR). Also, create a
BankManager class to manage accounts in any currency and modify
account balances.
Requirements:

o Use templates to define the Account<T> class.


o The BankManager class should access and modify the
balance of any Account<T> object, no matter what type
T is.
o The BankManager class should be a friend of
Account<T>.

Solution:
Part a:

#include <iostream>
#include <cmath> // For M_PI constant
using namespace std;

// Template Base class Shape with a pure virtual function getArea


template <typename T>
class Shape {
public:
virtual T getArea() const = 0; // Pure virtual function
};

// Template Derived class Rectangle inheriting from Shape


template <typename T>
class Rectangle : public Shape<T> {
private:
T length;
T width;

public:
Rectangle(T l, T w) : length(l), width(w) {}

// Override the getArea function for rectangle


T getArea() const override {
return length * width;
}
};

// Template Derived class Circle inheriting from Shape


template <typename T>
class Circle : public Shape<T> {
private:
T radius;

public:
Circle(T r) : radius(r) {}

// Override the getArea function for circle


T getArea() const override {
//return static_cast<T>(M_PI) * (radius * radius);
return 3.14 * (radius * radius);
}
};

// Main function
int main() {
cout<<"\n\n****Area of Rectangle and Circle for Integer Type of
Data****"<<endl;
// Create instances of Rectangle and Circle with integer type
Rectangle<int> rect(10, 5);
Circle<int> circ(6);

// Directly calculate and display the areas


cout << "Area of Rectangle: " << rect.getArea() << endl;
cout << "Area of Circle: " << circ.getArea() << endl<< endl<< endl;

cout<<"****Area of Rectangle and Circle for Double Type of


Data****"<<endl;
// Create instances of Rectangle and Circle with double type
Rectangle<double> rect1(5.5, 3.0);
Circle<double> circ1(4.0);

// Directly calculate and display the areas


cout << "Area of Rectangle: " << rect1.getArea() << endl;
cout << "Area of Circle: " << circ1.getArea() << endl;

return 0;
}

Part b:

#include <iostream>
#include <conio.h>
using namespace std;
template <class T> // Template Class
class readData
{
T a; // private variable "a" of T type.
T b; // private variable "b" of T type.
public:
friend class Subtract; // class Subtract is friend of class
readData which means class Subtract can access the private data members
of class readData without any error.
void read() // Read function to take input from the user
{
cout << "\nEnter First Number : ";
cin >> a;
cout << "\nEnter Second Number : ";
cin >> b;
}
};
class Subtract
{
public:
void Sub()
{
readData<int> obj1; // int type object
readData<float> obj2; // float type object

cout << "Integer Type Data" << endl;


obj1.read(); // Accessing the read function of readData class
cout << "\nResult of Object 1" << endl;
cout << "Difference = " << obj1.a - obj1.b << endl; //
Subtraction of two int values
cout << "\nFloat Type Data" << endl;
obj2.read(); // Accessing the read function of readData class
cout << "\nResult of Object 2" << endl;
cout << "Difference = " << obj2.a - obj2.b << endl; //
Subtraction of two float values
}
};

int main()
{

Subtract s1; // object of class Subtract


s1.Sub(); // calling sub method of class Subtract
system("pause");
return 0;
}
Lab 14: Containers and Cursors

Covering Lectures: Lectures 40 - 42

Objective:

This Lab aims to give students a deep understanding of various STL


containers in C++.

Learning Outcomes:

After completing this lab, students can practice sequence, associative,


and container adapters and explore their properties and use cases.

Problem Statement:

Design a mini-library system that uses multiple STL containers:

 Use a map to store books with the book title as the key and the
book's information (author, publication year, etc.) as the value.
 Use a queue to manage a waiting list for borrowing a book.
 Use a vector to store the list of currently available books.
 Implement functionality for adding books, borrowing books, and
managing the waiting list.
Sample Output:
Practice Questions:

 Write a program that reads a string from the user, splits it into
words, and uses set to display all unique words in the string.
 Create a task scheduler that allows the users to add tasks with
different priorities (higher numbers indicate higher priority). The
tasks should be stored in a priority_queue, and the program should
always execute and remove the highest-priority task first.
Solution:

#include <iostream>
#include <map>
#include <queue>
#include <vector>
#include <string>
using namespace std;

struct Book {
string author;
int publicationYear;
};

int main() {
map<string, Book> library;
queue<string> waitlist;
vector<string> availableBooks;
int choice;
string title, author;
int year;

while (true) {
cout << "\n****Select the Option****\n";
cout << "\n1. Add Book\n2. Borrow Book\n3. Manage Waitlist\n4.
Exit\n";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter book title: ";
getline(cin, title);
cout << "Enter author: ";
getline(cin, author);
cout << "Enter publication year: ";
cin >> year;
library[title] = {author, year};
availableBooks.push_back(title);
cout << "Book added!\n";
break;

case 2:
if (availableBooks.empty()) {
cout << "No books available, added to waitlist.\n";
cout << "Enter your name: ";
cin.ignore();
getline(cin, title);
waitlist.push(title);
} else {
cout << "You borrowed: " << availableBooks.back()
<< endl;
availableBooks.pop_back();
}
break;

case 3:
if (!waitlist.empty()) {
cout << "Next in waitlist: " << waitlist.front() <<
endl;
waitlist.pop();
} else {
cout << "No one in the waitlist.\n";
}
break;

case 4:
return 0;

default:
cout << "Invalid choice. Try again.\n";
}
}
}
Lab 15: Exception Handling

Covering Lectures: Lectures 43

Objective:

This Lab aims to give students a complete understanding of Error


Handling techniques.

Learning Outcomes:

After completing this lab students will be able to practice different error-
handling techniques:

 Abnormal Termination
 Graceful termination
 Return the illegal value
 Return error code from function
 Exception handling.
Problem Statement:

Write a C++ program to create a method that takes a string as input that
must have vowels in it. For example, “Hello” is a valid input as it has two
vowels ‘e’ and ‘o’ while “XYZ” is not a valid input as the string has no
vowels.

Suppose a user enters a string with no vowel so arises an error. Apply the
given Error handling techniques to handle this error in your program.

 Graceful termination
 Exception handling.

Sample Output:
Practice Questions:

Write C++ programs for the above scenario using the given Error-Handling
techniques.

 Abnormal Termination
 Return the illegal value
 Return error code from function
Solution:

// Write a C++ program to create a method that takes a string as input


that must have vowels in it. For example, “Hello” is a valid input as
it has two vowels ‘e’ and ‘o’ while “XYZ” is not a valid input as the
string has no vowels.
// Suppose a user enters a string with no vowel so arises an error.
Apply the given Error handling techniques to handle this error in your
program.
//  Graceful termination
//  Exception handling.

#include <iostream>
#include <string>
#include <stdexcept>

using namespace std;

//Function to check vowels in the string


bool hasVowels(const string& str)
{
for (size_t i = 0; i < str.length(); i++)
{ char lowerCh = tolower(str[i]); // Convert to lowercase for case-
insensitive check
if (lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' || lowerCh ==
'o' || lowerCh == 'u')
{
return true;
}
}
return false;
}

// a. Graceful Termination
void gracefulTermination(const string& input) {
if (!hasVowels(input)) {
cout << "No vowels found! Gracefully terminating the program."
<< endl;
exit(1); // Graceful exit without abrupt termination
}
else
cout << "The string \"" << input << "\" is valid." << endl;
}

// b. Exception Handling
bool exceptionHandling(const string& input)
{
if (!hasVowels(input)) {
cout << "Error: No vowels found in the string!" << endl;
return false; // Indicate failure
}
cout << "The string \"" << input << "\" is valid." << endl;
return true; // Indicate success
}

int main() {
string input;
int in;

// Take input from user


cout << "Enter a string: ";
cin >> input;

// Choosing the mode of termination of the program


cout<< "Select the mode of Termination";
cout<< "\n 1. Graceful Termination\n 2. Exceptional Handling\n 3.
Exit\n";
cin >> in;

switch (in) {

case 1:
{
cout << "\n--- Graceful Termination ---\n";
gracefulTermination(input);
break;
}
case 2:
{
cout << "\n--- Exception Handling ---\n";
exceptionHandling(input);
break;
}
case 3:
return 0;

default:
std::cout << "Invalid choice.\n";
}

return 0;
}

You might also like