Lab Manual OOP
Lab Manual OOP
Lab No 01
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.
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:
};
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.
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:
Both of the objects Box1 and Box2 will have their own copy of data members.
The public data members of objects of a class can be accessed using the direct member access
operator (.).
Lab Tasks:
01:
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:
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
int main(){
Student xyz;
xyz.getdetails();
cout<<""<<endl;
cout<<""<<endl;
xyz.printdetails();
return 0;
}
Output:
7
Lab No 02
MyClass() { // Constructor
};
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
is public
Default constructor: C++ Default Constructor
#include <iostream>
// declare a class
class Wall {
private:
double length;
public:
Wall() {
length = 5.5;
}};
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.
#include <iostream>
// declare a class
class Wall {
private:
double length;
double height;
public:
length = len;
height = hgt; }
double calculateArea() {
}};
int main() {
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:
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:
X();
~X();
};
Lab Tasks:
01: Observe, execute, and provide output for the program given in the file for the
destructor and constructor.
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
~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
Background
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.
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
class A
// copyconstructor.
In the above case, copy constructor can be called in the following ways:
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.
#include<iostream>
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){
a = obj.a; }
void display(){
} };
int main(){
x.display();
y.display();
z.display();
z1.display();
z2.display();
16
z3.display();
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
Output:
18
19
Lab No 04
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
class Employee
{ int id;
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} };
return 0;
}
Output:
23
Lab No 05
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;
result = c1.addNumbers(c2);
Note: We cannot use operator overloading for fundamental data types like int, float, char and so
on.
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
... .. ...
... .. ... };
Here,
Unary operators operate on only one operand. The increment operator ++ and decrement
operator -- are examples of unary operators.
#include <iostream>
class Count {
private:
int value;
public:
Count() : value(5) {}
void operator ++ () {
++value; }
void display() {
int main() {
Count count1;
++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.
The above example works only when ++ is used as a prefix. To make ++ work as a postfix
we use this syntax.
// 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)
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.
Count operator ++ () {
// code }
// code }
Here, we have used the following code for prefix operator overloading:
Count operator ++ () {
Count temp;
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.
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.
result = num + 9;
When we overload the binary operator for user-defined types by using the code:
The operator function is called using the obj1 object and obj2 is passed as an argument to the
function.
28
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
void input() {
Complex temp;
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() {
complex1.input();
complex2.input();
result.output();
return 0;}
Output: ?
// 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:
#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;
}
}
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
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?
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:
// 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.
// 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;
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.
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
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical 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:
// body of subclass };
// Single inheritance
#include<iostream>
// base class
class Vehicle {
public:
Vehicle() {
};
// main function
int main() {
Output
This is a Vehicle
Lab Tasks:
02.Write a C++ program to read and print students’ information using two classes and simple inheritance.
41
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();
sr.putStudentResult();
cout<<" "<<endl;
fr.putStudentInfo();
fr.putStudentResult();
return 0;
}
43
Lab No 07
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:
// 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.
// multiple inheritance
#include<iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
};
// 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 Task
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
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
// 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
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
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.
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();
}
• 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;
}
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();
1.
obj1.display_message();
obj2.parent_class::display_message();
2. Through Pointer
derived_class obj;
ptr->parent_class::display_message();
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";
}
};
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
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
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.
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>
class Base
public:
58
void show() {
}};
public:
void show(){
int main(){
b = &d;
Output
Total Objects: 1
Base class
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>
class Base
public:
59
};
public:
void show()
}};
int main()
b = &d;
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.
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:
public:
width = a;
height = b;
};
The = 0 tells the compiler that the function has no body and above virtual function will be called
pure virtual function.
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.
3) If we do not override the pure virtual function in derived class, then derived class also
becomes abstract class.
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
};
}
private:
double base, height;
};
int main() {
Shape* shapes[] = {
new Circle(5.0),
new Square(10.0),
new Triangle(8.0, 6.0)
};
return 0;
}
63
Lab No 11
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.
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 {
... .. ...
... .. ...
#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
// forward declaration
class ClassB;
We can also use a friend Class in C++ using the friend keyword. For example,
class ClassB;
class ClassA {
... .. ...}
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.
#include <iostream>
// forward declaration
class ClassB;
class ClassA {
private:
int numA;
public:
ClassA() : numA(12) {} };
class ClassB {
private:
int numB;
public:
ClassB() : numB(1) {}
int add() {
ClassA objectA;
int main() {
67
ClassB objectB;
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
Program:
#include<iostream>
class friendfunc1 {
private:
float num1, num2;
public:
friendfunc1(float a, float b) : num1(a), num2(b) {}
class friendfunc2 {
private:
float num3, num4, num5;
public:
friendfunc2(float c, float d, float e) : num3(c), num4(d), num5(e)
{}
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;
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
int main() {
// Creating an object of the Distance class
Distance obj(5, 6.0);
return 0;
}
70
71
Lab No 12
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.
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
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;
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
Lab No 13
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
class class_name1
//code.....
public:
class_name variable_name;
//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
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
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
Lab Task:
#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
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:
#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];
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
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
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