0% found this document useful (0 votes)
23 views88 pages

Lab Manual OOP

Lab Manual OOP of computer systems engineering

Uploaded by

Swaira Riaz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
23 views88 pages

Lab Manual OOP

Lab Manual OOP of computer systems engineering

Uploaded by

Swaira Riaz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 88

1

Lab No 01

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To do hands-on practice on classes and Objects (OOP features).

Theory:

The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented programming
and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and methods
for manipulating that data into one neat package. The data and functions within a class are called
members of the class.

C++ Class Definitions

When you define a class, you define a blueprint for a data type. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations. For example, we defined the Box data type using the keyword class as
follows:
2

class Box {

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

The keyword public determines the access attributes of the members of the class that follow it. A
public member can be accessed from outside the class anywhere within the scope of the class
object. You can also specify the members of a class as private or protected which we will discuss
in a sub-section.

Define C++ Objects

A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables of
basic types. Following statements declare two objects of class Box:

Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members

The public data members of objects of a class can be accessed using the direct member access
operator (.).

Lab Tasks:

01:

 Write below given code, compile it and run it.


 Write output of code in below given box.
3

Program:

#include <iostream>
using namespace std;
class Box{
public:
double lenght;
double breadth;
double height;
};
int main(){
Box Box1;
Box Box2;
double volume=0.0;

Box1.height=5.0;
Box1.lenght=6.0;
Box1.breadth=7.0;

Box2.height=10.0;
Box2.lenght=12.0;
Box2.breadth=13.0;

volume=Box1.lenght*Box1.height*Box1.breadth;
cout<<"Volume of Box1: "<<volume<<endl;

volume=Box2.breadth*Box2.height*Box2.lenght;
cout<<"Volume of Box2: "<<volume<<endl;
return 0;
}
Output:

 Write another program(C++ CODE) with class and objects.


 Compile, run and write the output..
4

Program:

#include <iostream>
using namespace std;
class Array{
private:
int a[6];
public:
void fill()
{
cout<<"Enter 6 numbers"<<endl;
for(int i=0;i<6;i++)
{
cin>>a[i];
}
}
void display()
{
cout<<"The numbers entered:";
for(int i=0;i<6;i++)
{
cout<<a[i]<<" ";
}
}
int max()
{
int h=a[0];
for(int i=0;i<6;i++)
{
if(h<a[i])
{
h=a[i];
}
}
return h;
}
int min()
{
int h=a[0];
for(int i=0;i<6;i++)
{
if(h>a[i])
{
h=a[i];
}
}
return h;
}
};
5

int main(){
Array arr;
arr.fill();
arr.display();
cout<<" "<<endl;
cout<<"Maximum number: "<<arr.max()<<endl;
cout<<"Minimum number: "<<arr.min()<<endl;
return 0;
}
Output:

02: Write a program, that creates a class for a student, read and print student’s detail givin
bellow using class and object.

 name;
 rollNo;
 totalMarks;
 perc;

Two functions :

GetDetails();

PrintDetails();

Program:

#include <iostream>
using namespace std;
class Student{
private:
string name;
int rollNo;
int totalMarks;
float per;
public:
void getdetails(){
6

cout<<"Enter Name: ";


cin>>name;
cout<<"Enter Roll no: ";
cin>>rollNo;
cout<<"Enter Total Marks: ";
cin>>totalMarks;
cout<<"Enter percentage: ";
cin>>per;
}
void printdetails(){
cout<<"Name :"<<name<<endl;
cout<<"Roll no :"<<rollNo<<endl;
cout<<"Total Marks:"<<totalMarks<<endl;
cout<<"Percentage :"<<per<<endl;
}
};

int main(){
Student xyz;
xyz.getdetails();
cout<<""<<endl;
cout<<""<<endl;
xyz.printdetails();
return 0;
}
Output:
7

Lab No 02

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working of default constructor, parameterized


constructor, destructor.

Background : A constructor is a special type of member function that is called automatically


when an object is created. In C++, a constructor has the same name as that of the class and it
does not have a return type.

Syntax for Constructor

class MyClass { // The class

public: // Access specifier

MyClass() { // Constructor

cout << "Hello World!";

};

int main() {

MyClass myObj; // Create an object of MyClass (this will call the constructor)

return 0;

Here, the function MyClass() is a constructor of the class Myclass. Notice that the constructor

 has the same name as the class,


 does not have a return type, and
8

 is public
Default constructor: C++ Default Constructor

A constructor with no parameters is known as a default constructor. In the example


above, MyClass() is a default constructor.

// C++ program to demonstrate the use of default constructor

#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

public:

// default constructor to initialize variable

Wall() {

length = 5.5;

cout << "Creating a wall." << endl;

cout << "Length = " << length << endl;

}};

int main() {

Wall wall1;

return 0; }

Here, when the wall1 object is created, the Wall() constructor is called. This sets
the length variable of the object to 5.5.

Note: If we have not defined a constructor in our class, then the C++ compiler will automatically
create a default constructor with an empty code and no parameters.

1 C++ Parameterized Constructor


9

In C++, a constructor with parameters is known as a parameterized constructor. This is the


preferred method to initialize member data.

2 C++ Parameterized Constructor


// C++ program to calculate the area of a wall

#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

double height;

public:

// parameterized constructor to initialize variables

Wall(double len, double hgt) {

length = len;

height = hgt; }

double calculateArea() {

return length * height;

}};

int main() {

// create object and initialize data members

Wall wall1(10.5, 8.6);

Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;

cout << "Area of Wall 2: " << wall2.calculateArea();


10

return 0;}

Here, we have created a parameterized constructor Wall() that has 2 parameters: double
len and double hgt. The values contained in these parameters are used to initialize the member
variables' length and height.

When we create an object of the Wall class, we pass the values for the member variables as
arguments. The code for this is:

Wall wall1(10.5, 8.6);

Wall wall2(8.5, 6.3);

With the member variables thus initialized, we can now calculate the area of the wall with
the calculateArea() function.

Destructor: A destructor is also a special function which is called when created object is deleted.
Destructor functions are the inverse of constructor functions. They are called when objects are
destroyed (deallocated).

A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For
example:

class X {

public:

// Constructor for class X

X();

// Destructor for class X

~X();

};

Several rules govern the declaration of destructors. Destructors:

1. Do not accept arguments.


2. Cannot specify any return type (including void).
3. Cannot return a value using the return statement.
4. Cannot be declared as const, volatile, or static. However, they can be invoked for the
destruction of objects declared as const, volatile, or static.
11

5. Can be declared as virtual.

Lab Tasks:

01: Observe, execute, and provide output for the program given in the file for the
destructor and constructor.

C++ program to demonstrate the use of default constructor:

C++ program to calculate the area of a wall

02: Write a program of your choice that implements constructor overloading and a
destructor?

#include <iostream>
using namespace std;
class MyClass {
private:
int value;
public:

MyClass() {
value = 0;
cout << "Default constructor called." << endl;
}

MyClass(int val) {
value = val;
12

cout << "Parameterized constructor called with value


" << value << endl;
}

~MyClass() {
cout << "Destructor called for object with value "
<< value << endl;
}

void display() {
cout << "Value: " << value << endl;
}
};

int main() {
MyClass obj1;
MyClass obj2(42);
MyClass obj3(17);
obj1.display();
obj2.display();
obj3.display();
return 0;
}

Output:
13

Lab No 03

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working of copy constructor

Background

Copy Constructor in C++

A copy constructor is a type of constructor that creates a copy of another object. If we want one
object to resemble another object, we can use a copy constructor. The copy constructor is a
constructor which creates an object by initializing it with an object of the same class, which has
been created previously.

If no copy constructor is written in the program compiler will supply its own copy constructor. If
the class has pointer variables and has some dynamic memory allocations, then it is a must to
have a copy constructor.

The copy constructor is used to:

1. Initialize one object from another of the same type.

2. Copy an object to pass it as an argument to a function.

3. Copy an object to return it from a function.

Copy Constructor is of two types:

o Default Copy constructor: The compiler defines the default copy constructor. If the user
defines no copy constructor, compiler supplies its constructor.
o User Defined constructor: The programmer defines the user-defined constructor.
14

Syntax Of User-defined Copy Constructor:

1. Class_name(const class_name &old_object);

Consider the following situation:

class A

A(A &x) // copy constructor.

// copyconstructor.

In the above case, copy constructor can be called in the following ways:

Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the same class type. For
example, Student s1 = s2, where Student is the class.
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.

An example program to demonstrate the concept of a Copy constructor in C++ is shown


below.

#include<iostream>

using namespace std;


15

class Number{

int a;

public:

Number(){

a = 0;

Number(int num){

a = num;

// When no copy constructor is found, compiler supplies its own copy constructor

Number(Number &obj){

cout<<"Copy constructor called!!!"<<endl;

a = obj.a; }

void display(){

cout<<"The number for this object is "<< a <<endl;

} };

int main(){

Number x, y, z(45), z2;

x.display();

y.display();

z.display();

Number z1(z); // Copy constructor invoked

z1.display();

z2 = z; // Copy constructor not called

z2.display();
16

Number z3 = z; // Copy constructor invoked

z3.display();

// z1 should exactly resemble z or x or y

return 0; }

Lab Task:

1.Observe, execute and provide output for the program given in file?

Output:

2. Write a C++ program that implements all three types of constructors and their usage in
constructing an object.

Program:

#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double breadth;
public:
Rectangle() {}
Rectangle(double l, double b) {
length = l;
breadth = b;
}
Rectangle(const Rectangle &obj) {
length = obj.length;
breadth = obj.breadth;
}
double calculateArea() {
17

return length * breadth;


}
};
int main() {
Rectangle obj(1, 2);
Rectangle obj1(5, 4);
Rectangle obj2 = obj1;
cout << "Area of Rectangle: " << obj.calculateArea() <<
endl;
cout << "Area of Rectangle 1: " << obj1.calculateArea() <<
endl;
cout << "Area of Rectangle 2: " << obj2.calculateArea() <<
endl;
return 0;
}

Output:
18
19

Lab No 04

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working of Array of Objects

When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array of objects.

Example#1:
Storing more than one Employee data. Let’s assume there is an array of objects for storing employee data
emp[50].
20

Below is the C++ program for storing data of one Employee:

// C++ program to implement


// the above approach
#include<iostream> using
namespace std;

class Employee
{ int id;

char name[30]; public:


void getdata();//Declaration of function void
putdata();//Declaration of function

}; void Employee::getdata(){//Defining of function


cout<<"Enter Id : "; cin>>id; cout<<"Enter Name : ";
cin>>name; }

void Employee::putdata(){//Defining of function


cout<<id<<" "; cout<<name<<" "; cout<<endl; } int
main(){

Employee emp; //One member


21

emp.getdata();//Accessing the function


emp.putdata();//Accessing the function
return 0; }

Let’s understand the above example –


• In the above example, a class named Employee with id and name is being considered.
• The two functions are declared-
• getdata(): Taking user input for id and name.
• putdata(): Showing the data on the console screen.
This program can take the data of only one Employee. What if there is a requirement to add data of more
than one Employee. Here comes the answer Array of Objects. An array of objects can be used if there is a
need to store data of more than one employee.

Advantages of Array of Objects:


1. The array of objects represent storing multiple objects in a single name.
2. In an array of objects, the data can be accessed randomly by using the index number.
3. Reduce the time and memory by storing the data in a single variable.

Lab Task:
Write a program that uses a method to initialize the Array of objects with parameterized
constructors:
Hint: class name object[] = { calling parametrize constructor(3 times)}
Quiz obj[] = { Quiz (1, 1), Quiz (2, 2), Quiz (3, 3) };
Program:
#include <iostream>
#include <string>
using namespace std;
class IceCream {
public:
string flavor;
int scoops;
IceCream(const string& f, int s) {
flavor = f;
scoops = s;
}
void display() {
cout << "Flavor: " << flavor << ", Scoops: " << scoops << endl;
}
22

};
int main() {
IceCream iceCreams[] = { {"Vanilla", 2}, {"Chocolate", 3},
{"Strawberry", 1} };

cout << "Initialized array of ice cream objects:" << endl;

for (int i = 0; i < 3; ++i) {


iceCreams[i].display();
}

return 0;
}
Output:
23

Lab No 05

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working Operator Overloading

1.Background

In C++, we can change the way operators work for user-defined types like objects and structures.
This is known as operator overloading. For example, suppose we have created three
objects c1, c2 and result from a class named Complex that represents complex numbers.

Since operator overloading allows us to change how operators work, we can redefine how
the + operator works and use it to add the complex numbers of c1 and c2 by writing the
following code:
24

result = c1 + c2;

instead of something like

result = c1.addNumbers(c2);

This makes our code intuitive and easy to understand.

Note: We cannot use operator overloading for fundamental data types like int, float, char and so
on.

2. Syntax for C++ Operator Overloading

To overload an operator, we use a special operator function. We define the function inside the
class or structure whose objects/variables we want the overloaded operator to work with.

class className {

... .. ...

public

returnType operator symbol (arguments) {

... .. ...

... .. ... };

Here,

 Return Type is the return type of the function.


 operator is a keyword.
 symbol is the operator we want to overload. Like: +, <, -, ++, etc.
 arguments is the arguments passed to the function.

3. Operator Overloading in Unary Operators

Unary operators operate on only one operand. The increment operator ++ and decrement
operator -- are examples of unary operators.

Example1: ++ Operator (Unary Operator) Overloading

// Overload ++ when used as prefix


25

#include <iostream>

using namespace std;

class Count {

private:

int value;

public:

// Constructor to initialize count to 5

Count() : value(5) {}

// Overload ++ when used as prefix

void operator ++ () {

++value; }

void display() {

cout << "Count: " << value << endl; }};

int main() {

Count count1;

// Call the "void operator ++ ()" function

++count1;

count1.display();

return 0; }

Output

Here, when we use ++count1;, the void operator ++ () is called. This increases
the value attribute for the object count1 by 1.
26

Note: When we overload operators, we can use it to work in any way we like. For example, we
could have used ++ to increase value by 100.

However, this makes our code confusing and difficult to understand. It's our job as a programmer
to use operator overloading properly and in a consistent and intuitive way.

4. Overload ++ when used as postfix

The above example works only when ++ is used as a prefix. To make ++ work as a postfix
we use this syntax.

void operator ++ (int) {

// code

Notice the int inside the parentheses. It's the syntax used for using unary operators as
postfix; it's not a function parameter. (Task)

5. Note:if we try to do something like :,

Count count1, result;

result = ++count1;

it doesn't work:

// Error

This is because the return type of our operator function is void. We can solve this problem by
making Count as the return type of the operator function.

// return Count when ++ used as prefix

Count operator ++ () {

// code }

// return Count when ++ used as postfix


27

Count operator ++ (int) {

// code }

Here, we have used the following code for prefix operator overloading:

// Overload ++ when used as prefix

Count operator ++ () {

Count temp;

// Here, value is the value attribute of the calling object

temp.value = ++value;

return temp; }

The code for the postfix operator overloading is also similar. Notice that we have created an
object temp and returned its value to the operator function.

Also, notice the code

temp.value = ++value;

The variable value belongs to the count1 object in main() because count1 is calling the function,
while temp.value belongs to the temp object.

Operator Overloading in Binary Operators

Binary operators work on two operands. For example,

result = num + 9;

Here, + is a binary operator that works on the operands num and 9.

When we overload the binary operator for user-defined types by using the code:

obj3 = obj1 + obj2;

The operator function is called using the obj1 object and obj2 is passed as an argument to the
function.
28

Example 4: C++ Binary Operator Overloading

// C++ program to overload the binary operator +

// This program adds two complex numbers

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;

public:

// Constructor to initialize real and imag to 0

Complex() : real(0), imag(0) {}

void input() {

cout << "Enter real and imaginary parts respectively: ";

cin >> real;

cin >> imag; }

// Overload the + operator

Complex operator + (const Complex& obj) {

Complex temp;

temp.real = real + obj.real;

temp.imag = imag + obj.imag;

return temp; }

void output() {

if (imag < 0)

cout << "Output Complex number: " << real << imag << "i";
29

else

cout << "Output Complex number: " << real << "+" << imag << "i"; }};

int main() {

Complex complex1, complex2, result;

cout << "Enter first complex number:\n";

complex1.input();

cout << "Enter second complex number:\n";

complex2.input();

// complex1 calls the operator function

// complex2 is passed as an argument to the function

result = complex1 + complex2;

result.output();

return 0;}

Output: ?

In this program, the operator function is:

Complex operator + (const Complex& obj) {

// code }

Instead of this, we also could have written this function like:

Complex operator + (Complex obj) { // code }

However,
30

 using & makes our code efficient by referencing the complex2 object instead of making a
duplicate object inside the operator function.
 using const is considered a good practice because it prevents the operator function from
modifying complex2.

Lab Task:

1: Write a code to implement Unary Operator (++Operator Overloading)when used as


prefix and postfix both?

#include <iostream>
using namespace std;
class Count{
private:
int n;
public:
Count(){
n=0;
}
void show(){
cout<<"n= "<<n<<endl;
}
Count operator ++(){
Count temp;
n=n+1;
temp.n=n;
31

return temp;
}
Count operator ++(int){
Count temp;
n=n+1;
temp.n=n;
return temp;
}
};
int main(){
Count x;
x.show();
++x;
x++;
x.show();
}

2: Write a code that uses Return type to Return Value from Binary Operator Function (+
Operator)

#include <iostream>
using namespace std;
class Add{
private:
int a,b;
public:
Add(){
a=b=0;
}
void in(){
cout<<"Enter a: ";
cin>>a;
cout<<"Enter b: ";
cin>>b;
}
void show(){
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
}
Add operator +(Add p){
Add temp;
temp.a=p.a+a;
temp.b=p.b+b;
return temp;}
};
32

int main(){
Add x,y,z;
x.in();
y.in();
z=x+y;
x.show();
y.show();
z.show();
}

3.Write a program that use some other operators of your choice (for operator
overloading)like relational operators etc.

Program:

#include <iostream>
#include <string.h>
using namespace std;
class String{
private:
char str[50];
public:
String(){
str[0]='\0';}
void in(){
cout<<"Enter String:";
gets(str);}

void show(){
cout<<str<<endl;}
int operator==(String s){
if(strlen(s.str)==strlen(str))
return 1;
else
return 0;
}
};
int main()
{
String s1,s2;
33

s1.in();
s2.in();
cout<<"s1= ";
s1.show();
cout<<"s2= ";
s2.show();
if(s1==s2){
cout<<"Both strings are of equal length."<<endl;}
else
{cout<<"Both strings are of different length."<<endl;
}
}

Things to Remember in C++ Operator Overloading

1. Two operators = and & are already overloaded by default in C++. For example, to copy
objects of the same class, we can directly use the = operator. We do not need to create an
operator function.
2. Operator overloading cannot change the precedence and associativity of operators.
However, if we want to change the order of evaluation, parentheses should be used.
3. There are 4 operators that cannot be overloaded in C++. They are:
0. :: (scope resolution)
a. . (member selection)
b. .* (member selection through pointer to function)
c. ?: (ternary operator)
34
35

Lab No 06

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the Basics of Inheritance

Background

Inheritance in C++

The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important features of Object-Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base Class or Super class.
In this lab we are going to discuss the following topics?

1. Why and when to use inheritance?


2. Modes of Inheritance
3. Types of Inheritance
Why and when to use inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create these classes
avoiding inheritance then we have to write all of these functions in each of the three classes as shown in
below figure:
36

You can clearly see that above process results in duplication of same code 3 times. This increases the
chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a
class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class,
then we can simply avoid the duplication of data and increase re-usability. Look at the below diagram in
which the three classes are inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three times as we have
inherited rest of the three classes from base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we
have to follow the below syntax.
Syntax:

class subclass_name : access_mode base_class_name

// body of subclass

};

Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to inherit
this sub class for example: public, private etc. and base_class_name is the name of the base class from
which you want to inherit the sub class.
37

Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full
parent object, which contains any private members which that class declares.

// C++ program to demonstrate implementation

// of Inheritance

#include <bits/stdc++.h>
using namespace std;
// Base class
class Parent {
public:
int id_p; };
// Sub class inheriting from Base Class(Parent)
class Child : public Parent
{
public:
int id_c;
};

// main function
int main()
{
Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is: " << obj1.id_c << '\n';
cout << "Parent id is: " << obj1.id_p << '\n';

return 0;
}

Output

Child id is 7

Parent id is 91

In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data
members of the class ‘Parent’ will also be inherited by the class ‘Child’.
Modes of Inheritance

1. Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.
38

2. Protected mode: If we derive a sub class from a Protected base class. Then both public member
and protected members of the base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
Note: The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed. For example, Classes B, C and D all contain the variables x,
y and z in below example. It is just question of access.

// C++ Implementation to show that a derived class

// doesn’t inherit access to private data members.

// However, it does inherit a full parent object.

class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for
classes
{
// x is private
// y is private
// z is not accessible from D
};

The below table summarizes the above three modes and shows the access specifier of the members of
base class in the sub class when derived in public, protected and private modes:
39

Types of Inheritance in C++

1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid (Virtual) Inheritance

In this lab we will discus Single inheritance

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub
class is inherited by one base class only.

Syntax:

class subclass_name : access_mode base_class {

// body of subclass };

// C++ program to explain


40

// Single inheritance

#include<iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() {

cout << "This is a Vehicle\n"; } };

// sub class derived from a single base classes

class Car : public Vehicle {

};

// main function

int main() {

// Creating object of sub class will

// invoke the constructor of base classes

Car obj; return 0; }

Output

This is a Vehicle

Lab Tasks:

01.Observe and execute the above c++ programs.

02.Write a C++ program to read and print students’ information using two classes and simple inheritance.
41

Program should contain:

Class contains student basic information with two functions to get student basic information and to put
student basic information. A derived class contains student Result information with two member
functions to get student result information and to put result information. Read and print Student basic
information and result information using object of derived class

#include <iostream>
#include <string>
using namespace std;
class StudentInfo {
protected:
string name;
int rollNo;

public:
void getStudentInfo() {
cout << "Enter the student's name: ";
cin >> name;
cout << "Enter the student's roll number: ";
cin >> rollNo;
}
void putStudentInfo() {
cout << "Student Name: " << name << endl;
cout << "Student Roll Number: " << rollNo << endl;
}
};
class StudentResult : public StudentInfo {
private:
int marks;

public:
void getStudentResult() {
cout << "Enter the student's marks: ";
cin >> marks;
}
void putStudentResult() {
cout << "Student Marks: " << marks << endl;
}
};
int main() {
StudentResult sr,fr;

sr.getStudentInfo();
sr.getStudentResult();
fr.getStudentInfo();
fr.getStudentResult();

cout << "\nStudent Details: "<<endl;


sr.putStudentInfo();
42

sr.putStudentResult();
cout<<" "<<endl;
fr.putStudentInfo();
fr.putStudentResult();
return 0;
}
43

Lab No 07

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working of Multiple Inheritance

Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than
one classes. i.e one sub class is inherited from more than one base classes.

Syntax:

class subclass_name : access_mode base_class1, access_mode base_class2, ....

// body of subclass

};
44

Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every base class
must be specified.

// C++ program to explain

// multiple inheritance

#include<iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {

};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output

This is a Vehicle

This is a 4 wheeler Vehicle


45

Lab Task

01.Observe and execute above c++ code.

02. Make a class named flower with a data member to calculate the number of flowers in a basket. Create
two other class named Rose and Jasmine to calculate the number of rose and jasmine in the basket. Print
the number of flowers of each type and the total number of flowers in the basket.

#include <iostream>
using namespace std;
class Flower {
protected:
int numFlowers;
public:
void calculateNumFlowers(int flowers) {
numFlowers += flowers;
}

int getNumFlowers() {
return numFlowers;
}
};
class Rose : public Flower {
private:
int numRoses;
public:
void calculateNumRoses(int roses) {
numRoses += roses;
calculateNumFlowers(roses);
}

int getNumRoses() {
return numRoses;
}
};
class Jasmine : public Flower {
private:
int numJasmines;
public:
void calculateNumJasmines(int jasmines) {
numJasmines += jasmines;
calculateNumFlowers(jasmines);
}
46

int getNumJasmines() {
return numJasmines;
}
};
int main() {
Rose rose;
Jasmine jasmine;
int roses, jasmines;
cout << "Enter the number of roses: ";
cin >> roses;
rose.calculateNumRoses(roses);
cout << "Enter the number of jasmines: ";
cin >> jasmines;
jasmine.calculateNumJasmines(jasmines);
cout << "\nNumber of roses: " << rose.getNumRoses() << endl;
cout << "Number of jasmines: " << jasmine.getNumJasmines() <<
endl;
cout << "Total number of flowers: " << rose.getNumFlowers() +
jasmine.getNumFlowers() << endl;

return 0;
}
47

Lab No 08

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working of Multilevel Inheritance

Multilevel Inheritance:

In multilevel inheritance a subclass is inherited from another subclass. It is not uncommon that a class is
derived from another derived class as shown in the figure "Multilevel Inheritance". Multilevel Inheritance
The class A serves as a base class for the derived class B, which in turn serves as a base class for the
derived class C. The class B is known as intermediate base class since it provides a link for the
inheritance between A and C.

class A{

//Do something

class B : public A{

//Do something

class C : public B{

//Do something

In this type of inheritance, a derived class is created from another derived class.
48

// C++ program to implement

// Multilevel Inheritance

#include<iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle\n"; }};
// first sub_class derived from class vehicle
class fourWheeler: public Vehicle
{ public:
fourWheeler() {
cout << "Objects with 4 wheels are vehicles\n"; }};
// sub class derived from the derived base class fourWheeler
class Car: public fourWheeler {
public:
Car() {
cout << "Car has 4 Wheels\n"; } };
// main function
int main() {
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0; }

Lab tasks:
49

01. Observe and Execute the above C++ program.


Output:

02. Write a C++ code that uses multilevel inheritance structure, based on any real life problem
statement of your own choice.
#include <iostream>
using namespace std;
class Person {
public:
void sleep() {
cout << "The person is sleeping." << std::endl;
}
};
class Student : public Person {
public:
void study() {
cout << "The student is studying." << std::endl;
}
};
class Examinee : public Student {
public:
void takeExam() {
cout << "The examinee is taking an exam." << std::endl;
}
};
class HighlyStressedStudent : public Examinee {
public:
void dealWithTension() {
cout << "The highly stressed student is dealing with tension."
<< std::endl;
}
};
int main() {
HighlyStressedStudent hss;
hss.sleep();
hss.study();
hss.takeExam();
hss.dealWithTension();
50

return 0;
}
51

Lab No 09

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement and understand the working of Run Time Polymorphism

Method Overriding in C++

Function overriding, in object-oriented programming, is a language feature that allows a subclass or child
class to provide a specific implementation of a method that is already provided by one of its super classes
or parent classes.

OR

Function overriding provides you with a way to override an existing functionality of a class inside a
particular derived class. This can be useful when a child class requires its own version of a functionality.

Example of Method Overriding in C++

Here we created a class named Base class and another class named Derived class which inherits all
properties of base class publicly. Both classes have same function named show with same function
prototype, however both print different message according to their respective class’s. Thus the
functionality is different. In the main function we created 2 objects of each of these classes and called
their respective show functions. when the function of the derived class show is called, it overrides the
base function show and prints “Derived class” instead of Base class. This is Function overriding.

#include<iostream>
using namespace std;
class Base
{
public:
void show()
{
cout << "Base class\t";
}
};
class Derived:public Base
52

{
public:
void show()
{
cout << "Derived Class";
}
};
int main()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Occurs
d.show();
}

Base class Derived Class

• There are different ways of calling overridden function from the child class:

As we have discussed in part 01of this lab ,that when we make the call to function (involved in
overriding), the child class function (overriding function) gets called. What if you want to call the
overridden function by using the object of child class. You can do that by creating the child class object in
such a way that the reference of parent class points to it. Lets take an example to understand it.

#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
/* Reference of base class pointing to
* the object of child class.
*/
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}

Function of Parent Class

If you want to call the Overridden function from overriding function then you can do it like this:
53

parent_class_name::function_name

To do this in the above example, we can write following statement in the disp() function of child class:

BaseClass::disp();

There are two other ways for accessing overridden method:

1.

derived_class obj1, obj2;

// call the overriding function

obj1.display_message();

// call the overridden function of the Base class

obj2.parent_class::display_message();

2. Through Pointer

// create instances of the derived class

derived_class obj;

// pointer of base class type

parent_class *ptr = &obj;

// call the parent class function

ptr->parent_class::display_message();

// call the overridden function

ptr->display_message();

Lab Tasks

1.Write a program that calculates Area of any two 2-D shapes(circle and rectangle) in base class method
and area of square in the method of derived class using method overriding.

Program:

#include<iostream>
#include<cmath>
using namespace std;
class Shape {
public:
virtual double getArea() {
return 0;
54

}
};
class Circle : public Shape {
private:
double radius;

public:
Circle(double radius) {
this->radius = radius;
}
double getArea() {
return 3.14159 * pow(radius, 2);
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double length, double width) {
this->length = length;
this->width = width;
}
double getArea() {
return length * width;
}
};
int main() {
Circle circle(5);
Rectangle rectangle(5, 6);
cout << "Area of Circle: " << circle.getArea() << endl;
cout << "Area of Rectangle: " << rectangle.getArea() << endl;
return 0;
}
Output:

2. Consider a class Carvehicle manufacturing company “Ford”. A “Car” manufactured by this company
inherits properties like brand name and vehicle type i.e. “Four Wheeler” from it. However, the “Car” can
have a more specific vehicle type like “Sports vehicle”. So, the vehicle type function of the class “Ford”
can be overridden in the class “Car” having its own definition of the function.

Write a program that implements method overriding by following the discussion given above.
55

Program:

#include<iostream>
using namespace std;
class VehicleManufacturingCompany {
public:
string brandName;
VehicleManufacturingCompany(string brandName) {
this->brandName = brandName;
}
virtual string getVehicleType() {
return "Four-Wheeler";
}
};

class Car : public VehicleManufacturingCompany {


public:
Car(string brandName) : VehicleManufacturingCompany(brandName) {}
string getVehicleType() {
return "Sports vehicle";
}
};

int main() {
VehicleManufacturingCompany vehicleManufacturingCompany("Ford");
Car car("Ford");
cout << "Vehicle type of the company " <<
vehicleManufacturingCompany.brandName << ": " <<
vehicleManufacturingCompany.getVehicleType() << endl;
cout << "Vehicle type of the car " << car.brandName << ": " <<
car.getVehicleType() << endl;
return 0;
}
Output:

3. Write a c++ program that implements one of the above technique/ways for calling overridden
function.

Program:

#include <iostream>
using namespace std;
class Base {
public:
virtual void display_message() {
56

cout << "This is the base class display_message function" <<


endl;
}
};
class Derived: public Base {
public:
void display_message() override {
cout << "This is the derived class display_message function"
<< endl;
}
};

int main() {
Derived obj1, obj2;
// call the overriding function
obj1.display_message();
// call the overridden function of the Base class
obj2.Base::display_message();
return 0;
}

Output:
57

Lab No 10

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement concept of virtual function and Late binding

Introduction.
Run Time/Late Binding/Dynamic polymorphism can be achieved using Virtual Functions in C+
+.

Virtual Function is a function in base class, which is overrided in the derived class, and which
tells the compiler to perform Late Binding / Dynamic Polymorphism on this function. Virtual
Keyword is used to make a member function of the base class Virtual.

Late Binding

In Late Binding function call is resolved at runtime. Hence, now compiler determines the type of
object at runtime, and then binds the function call. Late Binding is also called Dynamic Binding
or Runtime Binding.

Problem without Virtual Keyword

In this program you can see that even when we use the base class object to call the function of
child class, it calls the base class function. This results in early binding which is not what we
want. This problem can be resolved using the virtual keyword

#include<iostream>

using namespace std;

class Base

public:
58

void show() {

cout << "Base class";

}};

class Derived:public Base {

public:

void show(){

cout << "Derived Class";} };

int main(){

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Early Binding Ocuurs

Output

Total Objects: 1
Base class

Using Virtual Keyword

We can make base class’s methods virtual by using virtual keyword while declaring them.
Virtual keyword will lead to Late Binding of that method. In this program given below you can
see that we have made the base class function show as virtual by using the virtual keyword. Now
in the main function we are called the derived class function using the base class pointer object.
this is known as late binding or dynamic polymorphism

#include<iostream>

using namespace std;

class Base

public:
59

virtual void show()

cout << "Base class";

};

class Derived:public Base

public:

void show()

cout << "Derived Class";

}};

int main()

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show(); //Late Binding Ocuurs

Some important Facts about Virtual Function

1) Virtual functions ensure that the correct function is called for an object, regardless of the type
of reference (or pointer) used for function call.

2) They are mainly used to achieve Runtime polymorphism

3) Functions are declared with a virtual keyword in base class.

4) The resolving of function call is done at Run-time.


60

Pure Virtual Functions

It’s possible that you’d want to include a virtual function in a base class so that it may be
redefined in a derived class to suit the objects of that class, but that there is no meaningful
definition you could give for the function in the base class. We can change the virtual function
area() in the base class to the following:

class Shape {

protected:

int width, height;

public:

Shape( int a = 0, int b = 0) {

width = a;

height = b;

// pure virtual function

virtual int area() = 0;

};

The = 0 tells the compiler that the function has no body and above virtual function will be called
pure virtual function.

Abstract base classes

Classes which have pure virtual functions(such as the one in the above example) are known
as Abstract base classes or simply Abstract class. Abstract base classes cannot be used to
instantiate objects. But an abstract base class is not totally useless. It can be used to create
pointers to it, and take advantage of all its polymorphic abilities. Pure Virtual Functions &
Abstract Class in C++ - Sometimes implementation of all function cannot be provided in a base
class because we don’t know the implementation. Such a class is called abstract class.

Some important facts –

1) A class is abstract if it has at least one pure virtual function.

2) We can have pointers and references of abstract class type.


61

3) If we do not override the pure virtual function in derived class, then derived class also
becomes abstract class.

4) Abstract classes cannot be instantiated.

Lab Task:

Create a simple “shape” hierarchy: a base class called Shape and derived classes called Circle,
Square, and Triangle. In the base class, make a virtual function called draw( ), and override this
in the derived classes.

Program:

#include <iostream>
class Shape {
public:
virtual void draw() const = 0; // Pure virtual function, making
Shape an abstract class
};

class Circle : public Shape {


public:
Circle(double radius) : radius(radius) {}
void draw() const override {
std::cout << "Drawing a circle with radius " << radius <<
std::endl;
}
private:
double radius;
};

class Square : public Shape {


public:
Square(double side) : side(side) {}
void draw() const override {
std::cout << "Drawing a square with side " << side <<
std::endl;
}
private:
double side;
};

class Triangle : public Shape {


public:
Triangle(double base, double height) : base(base), height(height)
{}
void draw() const override {
std::cout << "Drawing a triangle with base " << base << " and
height " << height << std::endl;
62

}
private:
double base, height;
};

int main() {
Shape* shapes[] = {
new Circle(5.0),
new Square(10.0),
new Triangle(8.0, 6.0)
};

for (Shape* shape : shapes) {


shape->draw(); // Polymorphism in action
delete shape; // Free the memory
}

return 0;
}
63

Lab No 11

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement Friend Function and Friend Class

Introduction.
Data hiding is a fundamental concept of object-oriented programming. It restricts the access of
private members from outside of the class.

Similarly, protected members can only be accessed by derived classes and are inaccessible from
outside. For example,

class MyClass {
private:
int member1;}
int main() {
MyClass obj;
// Error! Cannot access private members from here.
obj.member1 = 5; }

However, there is a feature in C++ called friend functions that break this rule and allow us to
access member functions from outside the class.

Similarly, there is a friend class as well, which we will learn later in this tutorial.

friend Function in C++


64

A friend function can access the private and protected data of a class. We declare a friend
function using the friend keyword inside the body of the class.

class className {

... .. ...

friend returnType functionName(arguments);

... .. ...

Example 2: Add Members of Two Different Classes

// Add members of two different classes using friend functions

#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA {
public:
// constructor to initialize numA to 12
ClassA() : numA(12) {}
private:
int numA;
// friend function declaration
friend int add(ClassA, ClassB); };
class ClassB {
public:
// constructor to initialize numB to 1
ClassB() : numB(1) {}
private:
int numB;
// friend function declaration
friend int add(ClassA, ClassB); };
// access members of both classes
int add(ClassA objectA, ClassB objectB) {
return (objectA.numA + objectB.numB); }
int main() {
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
return 0; }
Output

Sum: 13
65

In this program, ClassA and ClassB have declared add() as a friend function. Thus, this function
can access private data of both classes.

One thing to notice here is the friend function inside ClassA is using the ClassB. However, we
haven't defined ClassB at this point.

// inside classA

friend int add(ClassA, ClassB);

For this to work, we need a forward declaration of ClassB in our program.

// forward declaration

class ClassB;

friend Class in C++

We can also use a friend Class in C++ using the friend keyword. For example,

class ClassB;

class ClassA {

// ClassB is a friend class of ClassA

friend class ClassB;

... .. ...}

class ClassB {

... .. ...

When a class is declared a friend class, all the member functions of the friend class become
friend functions.

Since ClassB is a friend class, we can access all members of ClassA from inside ClassB.

However, we cannot access members of ClassB from inside ClassA. It is because friend relation
in C++ is only granted, not taken.

Example 3: C++ friend Class

// C++ program to demonstrate the working of friend class


66

#include <iostream>

using namespace std;

// forward declaration

class ClassB;

class ClassA {

private:

int numA;

// friend class declaration

friend class ClassB;

public:

// constructor to initialize numA to 12

ClassA() : numA(12) {} };

class ClassB {

private:

int numB;

public:

// constructor to initialize numB to 1

ClassB() : numB(1) {}

// member function to add numA

// from ClassA and numB from ClassB

int add() {

ClassA objectA;

return objectA.numA + numB; } };

int main() {
67

ClassB objectB;

cout << "Sum: " << objectB.add();

return 0; }

Output

Sum: 13

Here, ClassB is a friend class of ClassA. So, ClassB has access to the members of classA.

In ClassB, we have created a function add() that returns the sum of numA and numB.

Since ClassB is a friend class, we can create objects of ClassA inside of ClassB.

Lab Tasks

1. Write a program to accept five different numbers by creating a class called


friendfunc1 and friendfunc2 taking 2 and 3 arg respectively and calculate the average

of these numbers by passing object of the class to friend function.

Program:

#include<iostream>

class friendfunc2; // Forward declaration for friend function

class friendfunc1 {
private:
float num1, num2;

public:
friendfunc1(float a, float b) : num1(a), num2(b) {}

friend void calculateAverage(friendfunc1 obj1, friendfunc2 obj2);


};

class friendfunc2 {
private:
float num3, num4, num5;

public:
friendfunc2(float c, float d, float e) : num3(c), num4(d), num5(e)
{}

friend void calculateAverage(friendfunc1 obj1, friendfunc2 obj2);


};
68

void calculateAverage(friendfunc1 obj1, friendfunc2 obj2) {


float average = (obj1.num1 + obj1.num2 + obj2.num3 + obj2.num4 +
obj2.num5) / 5.0f;
std::cout << "Average of the five numbers: " << average <<
std::endl;
}

int main() {
// Taking five different numbers as input
float num1, num2, num3, num4, num5;
std::cout << "Enter five different numbers: ";
std::cin >> num1 >> num2 >> num3 >> num4 >> num5;

// Creating objects of the classes


friendfunc1 obj1(num1, num2);
friendfunc2 obj2(num3, num4, num5);

// Passing objects to friend function to calculate average


calculateAverage(obj1, obj2);

return 0;
}

2. Make a class distance with data members feet and inches. Now , suppose we want a
function that will square (multiply by itself) an object of the Distance class and return the

result in square feet, as a type float. Using the concept of friend function implement this

Distance Class.

Program:

#include<iostream>

class Distance {
private:
int feet;
float inches;

public:
Distance(int ft, float in) : feet(ft), inches(in) {}
69

friend float squareDistance(const Distance& obj);


};

float squareDistance(const Distance& obj) {


float totalInches = (obj.feet * 12) + obj.inches;
float squareFeet = (totalInches * totalInches) / 144.0f; // 1
square foot = 144 square inches
return squareFeet;
}

int main() {
// Creating an object of the Distance class
Distance obj(5, 6.0);

// Calling the friend function to square the distance


float result = squareDistance(obj);

// Displaying the result


std::cout << "Square of the distance in square feet: " << result
<< std::endl;

return 0;
}
70
71

Lab No 12

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement Function Template

Introduction.
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as
a parameter so that we don’t need to write the same code for different data types.

How Templates Work


Templates are expanded at compiler time. This is like macros. The difference is, compiler does
type checking before template expansion. The idea is simple, source code contains only
function/class, but compiled code may contain multiple copies of same function/class.

Templates are of two type

1. Function Templates

2. Class Templates

Function Templates

We write a generic function that can be used for different data types. A single function template
can work with different data types at once but, a single normal function can only work with one
set of data types.
72

Normally function overloading can be used to perform different task on different data type but
templates are better approach to it.

Syntax

template <class class_name>


class_name function_name(class_name arg)
{
//code....
}

Example

#include <iostream.h>
Using namespace std;
//Defining Template function
template <class T>
T Greater(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
void main()
{
int a,b;
float c,d;
char c1, c2;
clrscr();
cout << "Enter two integer values:\n";
cin >>b>>a;
cout << Greater(a,b)<<" is greater." << endl;
cout << "\nEnter two floating-point values:\n";
cin >>c>>d;
cout <<Greater(c,d) <<" is Greater." << endl;
cout << "\nEnter two characters:\n";
cin >>c1>>c2;
cout <<Greater(c1, c2) << " has Greater ASCII value.";
getch();
}

Lab Task:

Convert the class provided into the file into a template Function, and then make a
version of template_test.cpp that demonstrates that it works.
73

#include <iostream>
using namespace std;
//Defining Template function
template <class T>
T Greater(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}

int main()
{
int a, b;
float c, d;
char c1, c2;

cout << "Enter two integer values:\n";


cin >> a >> b;
cout << Greater(a, b) << " is greater." << endl;

cout << "\nEnter two floating-point values:\n";


cin >> c >> d;
cout << Greater(c, d) << " is Greater." << endl;

cout << "\nEnter two characters:\n";


cin >> c1 >> c2;
cout << Greater(c1, c2) << " has Greater ASCII value.";

return 0;
}

This code defines a template function called Greater(). The function takes two parameters of the
same data type (T n1, T n2) and returns the greater value among the two. The data type (T) is a
placeholder that can be any valid data type (e.g., int, float, double, char, etc.). The main function
of the program prompts the user to enter two values of each data type (int, float, char). It then
uses the Greater() function to find the greater value among the entered pairs of values and prints
the result.
74

The program can be executed with the following steps:

 The program prompts the user to enter two integer values.


 The user inputs two integer values.
 The program displays the greater integer value.
 The program prompts the user to enter two floating-point values.
 The user inputs two floating-point values.
 The program displays the greater floating-point value.
 The program prompts the user to enter two characters.
 The user inputs two characters.
 The program displays the character with the greater ASCII value.
 After the program executes, it will have successfully determined the greater value among
the pairs of entered values, regardless of their data type.
75

Lab No 13

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement Class Template

Introduction:

Class Templates
Like function templates, class templates are useful when a class defines something that is
independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack,
Queue, Array, etc.
Sometimes, you need a class implementation that is same for all classes, only the data types used
are different.

Syntax

template <class class_name>

class class_name1

//code.....

public:

class_name variable_name;

class_name function_name(class_name arg);

//code.....

};

Example
76

#include <iostream>
using namespace std;
// Class template
template <class T>
class Number {
private:
// Variable of type T
T num;
public:
Number(T n) : num(n) {} // constructor
T getNum() {
return num; }};
int main() {
// create object with int type
Number<int> numberInt(7);
// create object with double type
Number<double> numberDouble(7.7);
cout << "int Number = " << numberInt.getNum() << endl;
cout << "double Number = " << numberDouble.getNum() << endl;
return 0;
}
Output

Lab Task

1. Convert the class provided into the file into a template class and observe the output.
#include <iostream>
using namespace std;
// Class template
template <class T>
class Number {
private:
// Variable of type T
T num;
public:
Number(T n) : num(n) {} // constructor
T getNum() {
return num; }};

int main() {
// create object with int type
Number<int> numberInt(6);
77

// create object with double type


Number<double> numberDouble(3.7);
cout << "int Number = " << numberInt.getNum() << endl;
cout << "double Number = " << numberDouble.getNum() << endl;
return 0;
}

2. Create a Class Template by considering two students in a class and we want to calculate
the total marks of each of them in two subjects. Suppose the marks of the first student in
both the subjects are integer values and that of the second student floating values.
#include <iostream>
using namespace std;
// Class template
template <class T1, class T2>
class StudentMarks {
private:
// Variables of type T1 and T2
T1 mark1;
T2 mark2;
public:
StudentMarks(T1 m1, T2 m2) : mark1(m1), mark2(m2) {} //
constructor
T1 getMark1() {
return mark1; };
T2 getMark2() {
return mark2; }};

int main() {
// create object with int and float marks
StudentMarks<int, float> student1(80, 85.5);
StudentMarks<int, float> student2(90, 95.5);
cout << "Student 1 Marks: " << student1.getMark1() << " and " <<
student1.getMark2() << endl;
cout << "Student 2 Marks: " << student2.getMark1() << " and " <<
student2.getMark2() << endl;
return 0;
}
78
79

Lab No 14

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement STL

Introduction:

The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide
general-purpose classes and functions with templates that implement many popular and
commonly used algorithms and data structures like vectors, lists, queues, and stacks.At the core
of the C++ Standard Template Library are following three well-structured components:

1. Containers
Containers are used to manage collections of objects of a certain kind. There are several
different types of containers like deque, list, vector, map etc.

2. Algorithms
Algorithms act on containers. They provide the means by which you will perform
initialization, sorting, searching, and transforming of the contents of containers.

3. Iterators
Iterators are used to step through the elements of collections of objects. These collections
may be containers or subsets of containers.

Let us take the following program that demonstrates the vector container (a C++ Standard
Template) which is similar to an array with an exception that it automatically handles its own
storage requirements in case it grows −

Live Demo

#include <iostream>
#include <vector>
using namespace std;
int main() {
80

// create a vector to store int


vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for(i = 0; i < 5; i++) {
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;

// access 5 values from the vector


for(i = 0; i < 5; i++) {
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++; }
return 0; }

Lab Task:

1.Write a code in C++ to demonstrate your understanding of STL.

#include <iostream>
#include <map>
#include <string>
using namespace std;
void updateInventory(map<string, int>& inventory, string item, int
quantity) {
inventory[item] += quantity;
}
void displayInventory(const map<string, int>& inventory) {
cout << "Inventory:" << endl;
for (const auto& item : inventory) {
cout << item.first << ": " << item.second << endl;}
}
int main() {
map<string, int> inventory;
updateInventory(inventory, "brownies", 50);
updateInventory(inventory, "cakes", 30);
updateInventory(inventory, "ice cream", 20);
displayInventory(inventory);
return 0;
}
81
82
83

Lab No 15

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Objective: To implement concept of Threading and Multithreading

Introduction
Multithreading is a feature that allows concurrent execution of two or more parts of a program
for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads
are lightweight processes within a process.

Example

This simple example code creates 5 threads with the pthread_create() routine. Each thread prints
a "Hello World!" message, and then terminates with a call to pthread_exit().

#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}

int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
84

if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}

Lab Task:

1.Write a code in C++ to demonstrate your understanding of thread/multithread in C++.

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx; // Mutex for critical section
void printThreadID(int id) {
mtx.lock(); // Lock mutex
cout << "Thread " << id << " is running" << endl;
mtx.unlock(); // Unlock mutex
}
int main() {
const int numThreads = 5;
thread threads[numThreads];

// Create and start 5 threads


for (int i = 0; i < numThreads; ++i) {
threads[i] = thread(printThreadID, i + 1);
}
// Join all threads
for (int i = 0; i < numThreads; ++i) {
threads[i].join();
}
return 0;
}
85

Object Oriented Programming

Open Ended Lab

Name: Nisma Munawar Roll No.: F22BCSEN1M01015

Submitted to: Dr. Nadia Rasheed Date:

Question/Task

1. The students are required to utilize the skill set acquired during lab work and
accomplish the task of OEL.

2. PLO-3 P-4

The main objective of this activity is to :


a) Create the C++ Function Template named multiples so that it has three parameters sum,
x, and n. The first two parameters will have the type represented by the function template
type parameter Kindof. n will always be int. The return type is void. All parameters are
passed by value except for sum which is passed by reference.
A Template Function created from multiples will compute...
sum = 1 + x + 2x + 3x + ... + nx

Program:
Input:
#include<iostream>
using namespace std;
template <typename Kindof>
void multiples(Kindof& sum, Kindof x, int n)
{
sum = 1;
for (int i = 1; i <= n; ++i)
{
sum += i * x;
}
}
int main()
{
int intSum = 0;
86

double doubleSum = 0.0;


multiples(intSum, 5, 3);
multiples(doubleSum, 2.5, 4);
std::cout << "Integer sum: " << intSum << std::endl;
std::cout << "Double sum: " << doubleSum << std::endl;
return 0;
}
Output:

b) Create a class called time that has separate int member data for hours, minutes, and
seconds. One constructor should initialize this data to 0, and another should initialize it
to fixed values. Another member function should display it, in 11:59:59 format. The final
member function should add two objects of type time passed as arguments

Program:
Input:
#include <iostream>
using namespace std;
class Time
{
private:
int hours;
int minutes;
int seconds;
public:
Time() : hours(0), minutes(0), seconds(0) {}
Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}
void display() const
{
cout << hours << ":" << minutes << ":" << seconds << endl;
}
Time add(const Time& other) const
{
int totalSeconds = seconds + other.seconds;
int carryMinutes = totalSeconds / 60;
totalSeconds %= 60;
int totalMinutes = minutes + other.minutes + carryMinutes;
int carryHours = totalMinutes / 60;
totalMinutes %= 60;
int totalHours = hours + other.hours + carryHours;
return Time(totalHours, totalMinutes, totalSeconds);
87

}
};
int main()
{
Time time1(10, 30, 45);
Time time2(2, 15, 20);
time1.display();
time2.display();
Time sum = time1.add(time2);
sum.display();
return 0;
}
Output:
88

You might also like