You are on page 1of 75

USHA MITTAL INSTITUTE OF TECHNOLOGY

 SNDT WOMEN’S UNIVERSITY

 MUMBAI – 400049

Name: Shruti Manoj Chavan

Roll No.: 14

Subject: Object Oriented Programming lab

Branch: Computer Science and Technology

Year: 2021-22
1
2
INDEX

SR. PAGE
AIM DATE
NO NO.

1 Structure program in C and compare it with Class program in C++ 15/9/21 5

Write a program to find Area of circle, triangle and rectangle


2 15/9/21 7
using function overloading

3 Design a C++ class using that reverses digits in entered numbers. 15/9/21 13

Design a class in C++ to find whether entered number is


4 15/9/21 15
Palindrome or not

Design a class to display a day in a week. Here giver input range


5 22/9/21 17
is from 1 to 7

Design a class to check if the given character is upper case lower


6 22/9/21 19
case or number or not

Write a program to calculate Gross Pay of the Regular, Daily


7 29/9/21 21
wages and Consolidated employees in Indian Railway

8 Implementation of call by value and call by reference 29/9/21 24

An electricity board charges the following rate to domestic


users to discourage large consumption of energy. For the first
100 units Rs.2 per unit for next 200 units Rs.3 per unit, beyond
300 units rate is Rs.5 per unit. All users are charged a minimum
9 of Rs.150. If the total amount is more than Rs.500 then 6/10/21 26
additional surcharge for GST 18% is added. Write a class in C++
to read the names of users and number of units consumed and
print out the readings with all details. The rates for commercial
purposes are double of the rates of domestic users.
10 Define a class to represent a bank account which includes 6/10/21 29
following member:

3
Data members: name of the depositor, account no., type of
account, balance amount in account
Member functions: To assign initial values, Deposit and amount,
withdraw (condition to check with deposit), display name and
balance
Use constructor for initialization of data members
Design a class Vector uses a constructor to initialize the values.
Vector class must perform following functionalities:
Create a vector
11 To modify the values of the given element in vector 20/10/21 32
To multiply by a scalar value
To display the vector
Use a destructor also.

Write a Menu given class in C++ which demonstrate simple


12 20/10/21 35
constructor, Parameterized constructor and copy constructor

Design a class complex and use friend function to access private


13 27/10/21 39
data members of the class

Design two different classes student and College, make college


14 27/10/21 41
class as a friend of student and access private data of class

Demonstrate how static data members and member function


15 27/10/21 43
works with an example

16 Design a class to overload +,-,* operator 17/11/21 45

17 Design a class to overload +++, -- operators 17/11/21 48

Design a class in cpp to convert basic data types to user defined


18 24/11/21 50
data types

Design a class in cpp to convert user defined data types to user


19 24/11/21 52
defined data types

Design a class in cpp to convert user defined data types to basic


20 24/11/21 54
data types

Design a class in cpp for Inheritance. Class student is a base


21 8/12/21 56
class having all the basic attributes and functionality... Derive
4
new class General Secretary, add some more attributes and
operations to the class
write a program to implement virtual base class, class name:
Teacher: teacher having attributes name, qualification and
salary. From teacher class two classes are derived
professor
visiting professor
22 8/12/21 59
professor having attribute: subject, semester and department
whereas visiting faculty having attributes: subject, renumeration
per hour, time. From professor and visiting professor a new class
is derived name as instructor. The attributes of the instructors
are: expertise in, conducting the workshop.

23 Demonstrate the use of virtual base class 8/12/21 62

Design a abstract class in cpp and make practically impossible to


24 15/12/21 65
instantiate the class

Prove that CPP is a robust language using exception handling


25 15/12/21 66
mechanisms and handle at least any 3 exceptions in one program.

26 Design a class in cpp to operate on string 15/12/21 68

Copy string, concatenate the string, delete string, convert lower


27 18/12/21 71
case to upper case, size of the string

Design a class in cpp to create a new file, modify the file and
28 18/12/21 73
save the content of the file

5
EXPERIMENT NO. 1

AIM: Structure program in C and compare it with Class program in C++.

Structure Program:

#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

int main()
{
Person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output:

Enter Full name: SHRUTI CHAVAN


Enter age: 20
Enter salary: 20000

Displaying Information.
Name: SHRUTI CHAVAN
6
Age: 20
Salary: 20000

Screenshot:

Class Function:

#include <iostream>
using namespace std;

// create a class
class Room
{

public:
double length,breadth,height;

double calculateArea()
{
return length * breadth;
}

double calculateVolume()
{
return length * breadth * height;
}
};

int main()
{

// create object of Room class


Room room1;

7
// assign values to data members
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Output:

Area of Room = 1309


Volume of Room = 25132.8

Screenshot:

8
EXPERIMENT NO. 2

AIM: Write a program to find Area of circle, triangle and rectangle using function
overloading

Program:

#include<iostream>
using namespace std;

class Shape
{
protected:
double x,y;

public:

virtual void get_data() = 0;


virtual void display_area()=0;
};

class Circle : public Shape


{
public:
void get_data()
{
cout<<"Enter Radius of Circle :";
cin>>x;
}

void display_area()
{
double ac;
ac = 3.14*x*x;
cout<<"Area of Circle is :"<<ac<<endl;
}
};

class Rectangle : public Shape


{
public:
void get_data()
{
cout<<"Enter Width and Length of Rectangle :";

9
cin>>x>>y;
}

void display_area()
{
double ar;
ar = x*y;
cout<<"Area of Rectangle is :"<<ar<<endl;
}
};

class Triangle : public Shape


{
public:
void get_data()
{
cout<<"Enter Height and Base of Triangle :";
cin>>x>>y;
}

void display_area()
{
double at;
at = 0.5* x*y;
cout<<"Area of Triangle is :"<<at<<endl;
}
};

class Square : public Shape


{
public:
void get_data()
{
cout<<"Enter Side of Square :";
cin>>x;
}

void display_area()
{
double as;
as = x*x;
cout<<"Area of Square is :"<<as <<endl;
}
};

int main()
{
10
Circle cr;
int op;
char choice;
Rectangle rect;
Triangle tr;
Square sr;

Shape *sh[4];
sh[0] = &cr;
sh[1] = &rect;
sh[2] = &tr;
sh[3] = &sr;

do
{
system("cls");
cout<<"===== Calculate Area of Different Shape ======"<<endl;
cout<<"1: Area of Circle "<<endl;
cout<<"2: Area of Rectangle "<<endl;
cout<<"3: Area of Triangle "<<endl;
cout<<"4: Area of Square "<<endl;
cout<<"Plz Enter Your Choice"<<endl;
cin>>op;

switch(op)
{
case 1:
sh[0]->get_data();
sh[0]->display_area();
break;

case 2:
sh[1]->get_data();
sh[1]->display_area();
break;

case 3:
sh[2]->get_data();
sh[2]->display_area();
break;

case 4:
sh[3]->get_data();
sh[3]->display_area();
break;

default:
11
cout<<"Invalid Number You Enter "<<endl;
}

cout<<"Do You Want to Calculate Another Area [Yes / No] :";


cin>>choice;
}
while(choice =='Y'||choice == 'y');
}

Output:
===== Calculate Area of Different Shape ======
1: Area of Circle
2: Area of Rectangle
3: Area of Triangle
4: Area of Square
Plz Enter Your Choice
1
Enter Radius of Circle :5
Area of Circle is :78.5
Do You Want to Calculate Another Area [Yes / No] :y

===== Calculate Area of Different Shape ======


1: Area of Circle
2: Area of Rectangle
3: Area of Triangle
4: Area of Square
Plz Enter Your Choice
2
Enter Width and Length of Rectangle :4 5
Area of Rectangle is :20
Do You Want to Calculate Another Area [Yes / No] :y

===== Calculate Area of Different Shape ======


1: Area of Circle
2: Area of Rectangle
3: Area of Triangle
4: Area of Square
Plz Enter Your Choice
3
Enter Height and Base of Triangle :40 9
Area of Triangle is :180
Do You Want to Calculate Another Area [Yes / No] :n

12
Screenshot:

13
EXPERIMENT NO. 3

AIM: Design a C++ class using that reverses digits in entered numbers.

Program:

#include<iostream>
using namespace std;

class Test
{
public: int reverse(int x)

{
int r, rev = 0;
while (x > 0)

{
r = x % 10;
rev = rev * 10 + r;
x = x / 10;
}

return rev;
}
};

int main()
{
int x, rev;
cout << "Enter a number:";
cin >> x;

Test obj;
rev = obj.reverse(x);
cout << "After reverse number is:" << rev;
return 0;
}

Output:

Enter a number:147352
After reverse number is:253741
14
Screenshot:

15
EXPERIMENT NO. 4

AIM: Design a class in C++ to find whether entered number is Palindrome or not

Program:

#include<iostream>
using namespace std;

class Test {
public:

int reverse(int x) {
int r, rev = 0;

while (x > 0) {
r = x % 10;
rev = rev * 10 + r;
x = x / 10;
}
return rev;
}
};

int main() {

int x, rev;

cout << "Enter a number:";


cin >> x;

Test obj;
rev = obj.reverse(x);

if (rev == x) {
cout << "Number is palindrome:" << x;
} else {
cout << "Number is not palindrome:" << x;
}

return 0;
}

16
Output:

Enter a number:48984
Number is palindrome:48984

Enter a number:12345
Number is not palindrome:12345

Screenshot:

17
EXPERIMENT NO. 5

AIM: Design a class to display a day in a week. Here giver input range is from 1 to
7

Program:

#include <iostream>
using namespace std;

int main()
{
int weeknumber;
cout<<"Enter week number(1-7): ";
cin>>weeknumber;
switch(weeknumber)
{
case 1: cout<<"Monday";
break;
case 2: cout<<"Tuesday";
break;
case 3: cout<<"Wednesday";
break;
case 4: cout<<"Thursday";
break;
case 5: cout<<"Friday";
break;
case 6: cout<<"Saturday";
break;
case 7: cout<<"Sunday";
break;
default: cout<<"Invalid input! Please enter week no. between 1-7.";
}
return 0;
}

Output:

Enter week number(1-7): 5


Friday

Enter week number(1-7): 8


Invalid input! Please enter week no. between 1-7.

18
Enter week number(1-7): 2
Tuesday C

Screenshot:

19
EXPERIMENT NO. 6

AIM: Design a class to check if the given character is upper case lower case or
number or not

Program:

#include<iostream>
using namespace std;
class ch1
{
public:
char ch;
int character(char ch)
{
if(ch>='A'&&ch<='Z')
cout<<endl<<"You entered an uppercase character";
else if(ch>='a'&&ch<='z')
cout<<endl<<"You entered a lowercase character";
else if(ch>='1'&&ch<='7')
cout<<endl<<"You entered a number";
else
cout<<endl<<"You entered a invalid input";
return 0;
}
};
int main()
{
char ch;
cout<<"Enter character:";
cin>>ch;
ch1 obj;
obj.character(ch);
return 0;
}

Output:

Enter character:A
You entered an uppercase character C

Enter character:f
20
You entered a lowercase character

Enter character:123
You entered a number

Enter character:'
You entered a invalid input

Screenshot:

21
EXPERIMENT NO. 7

AIM: Write a program to calculate Gross Pay of the Regular, Daily wages and
Consolidated employees in Indian Railway

Program:

#include<iostream>
using namespace std;

class GrossPay
{
public:
void salary(float basic,float hra,float DA)
{
float total_pay ;
total_pay= basic+(hra*basic/100)+ (DA*basic/100);
cout<<"Regular Salary is: "<<total_pay<<endl;
}

void salary(int wages_per_hour,int n)


{
int daily_wages;
daily_wages = wages_per_hour*n;
cout<<"Total daily wage is: "<<daily_wages<<endl;
}

void salary(float fixed)


{
cout<<"Consolidated pay is: "<<fixed<<endl;
}
};

int main()
{
float basic,hra,DA;
int wages_per_hour,n;
float fixed;
int choice;
GrossPay obj;
cout<<"--------------"<<endl;
cout<<"ENTER YOUR CHOICE"<<endl<<"1. Regular Employee"<<endl<<"2. Daily
Wages"<<endl<<"3. Consolidated pay"<<endl;
cout<<"--------------";
cin>>choice;
22
switch (choice)
{
case 1:
cout<<endl<<"Enter basic salary,hra percentage,DA percentage :"<<endl;
cin>>basic>>hra>>DA;
obj.salary(basic,hra,DA);
break;

case 2:
cout<<endl<<"Enter wage per hour and no.of hours: "<<endl;
cin>>wages_per_hour>>n;
obj.salary(wages_per_hour,n);
break;

case 3:
cout<<endl<<"Enter Consolidated pay amount: "<<endl;
cin>>fixed;
obj.salary(fixed);
break;

default:
cout<<"Invalid Choice";
break;
}
return 0;
}

Output:

---------------
ENTER YOUR CHOICE
1. Regular Employee
2. Daily Wages
3. Consolidated pay
---------------
1
Enter basic salary,hra percentage,DA percentage :
50000 15 10
Regular Salary is: 62500

---------------
ENTER YOUR CHOICE
1. Regular Employee
2. Daily Wages
3. Consolidated pay
---------------
2
23
Enter wage per hour and no.of hours:
1000 5
Total daily wage is: 5000

---------------
ENTER YOUR CHOICE
1. Regular Employee
2. Daily Wages
3. Consolidated pay
---------------
3
Enter Consolidated pay amount:
67000
Consolidated pay is: 67000

Screenshot:

24
EXPERIMENT NO. 8

AIM: Implementation of call by value and call by reference 

Program:

#include <iostream>
using namespace std;

class Callbyvalandref

{
public:
void calc(int a, int& b);

};

void Callbyvalandref::calc(int a, int& b)


{
cout<<"The value of a and b before calculation in the function is "<<a<<" and "<<b
<<endl;
a = a * 2;
b = b * 2;
cout<<"The value of a and b after calculation in the function is "<<a<<" and "<<b
<<endl;
}

int main()
{
int a, b;
Callbyvalandref obj;
a = 5;
b = 6;
cout<<"The value of a and b before calculation outside the function is "<<a<<" and
"<<b <<endl;

obj.calc(a, b);
cout<<"The value of a and b after calculation outside the function is "<<a<<" and
"<<b <<endl;

return 0;
}

25
Output:

The value of a and b before calculation outside the function is 5 and 6


The value of a and b before calculation in the function is 5 and 6
The value of a and b after calculation in the function is 10 and 12
The value of a and b after calculation outside the function is 5 and 12

Screenshot:

26
EXPERIMENT NO. 9

AIM: An electricity board charges the following rate to domestic users to discourage large
consumption of energy. For the first 100 units Rs.2 per unit for next 200 units Rs.3 per
unit, beyond 300 units rate is Rs.5 per unit. All users are charged a minimum of Rs.150. If
the total amount is more than Rs.500 then additional surcharge for GST 18% is added.
Write a class in C++ to read the names of users and number of units consumed and print
out the readings with all details. The rates for commercial purposes are double of the
rates of domestic users.

Program:

#include <iostream>
using namespace std;

class electricity{
public:
string name;
int units;
bool type;
int cost;

electricity (string n, int u, bool t){


name = n;
units = u;
type = t;
cost = 0;
if(units>=300){
cost = cost + 100*2;
units -=100;
cost = cost + 200*3;
units -=200;
cost = cost + units*5;
} else if(units>100){
cost = cost + 100*2;
units -= 100;
cost = cost + units*3;
}else{
cost = cost + units*2;
}
if(cost < 150) cost = 150;
if (!type) cost *= 2;
if (cost > 500) cost +=0.18*cost;
}

27
void bill () {
cout << "\n ******* ELECTRICITY BILL *******\n";
cout << "Name = " << name << endl;
cout << "Units = " << units << endl;
if(type)
cout << "Type of User = Domestic" << endl;
else
cout << " Type of User = Commercial" << endl;
cout << "Total Cost = Rs. " << cost << endl;
}
};

int main()
{
string name;
int units;
bool type;
cout << "Enter Costumer name: ";
cin >> name;
cout<< "Enter number of units consumed: ";
cin >> units;
cout << " Type of customer - 1. Domestic 2. Commercial: ";
cin >> type;
electricity c1(name, units, type);
c1.bill();
return 0;
}

Output:

Enter Costumer name: SHRUTI


Enter number of units consumed: 127
Type of customer - 1. Domestic 2. Commercial: 1

******* ELECTRICITY BILL *******


Name = SHRUTI
Units = 27
Type of User = Domestic
Total Cost = Rs. 281

Enter Costumer name: ELITE_CORP


Enter number of units consumed: 800
Type of customer - 1. Domestic 2. Commercial: 2

******* ELECTRICITY BILL *******


Name = ELITE_CORP
28
Units = 500
Type of User = Domestic
Total Cost = Rs. 3894

Screenshot:

29
EXPERIMENT NO. 10

AIM: Define a class to represent a bank account which includes following member:
 Data members: name of the depositor, account no., type of account, balance
amount in account
 Member functions: To assign initial values, Deposit and amount, Withdraw
(condition to check with deposit), display name and balance
 Use constructor for initialization of data members

Program:

#include<iostream>
#include<stdio.h>
#include<string.h>

using namespace std;

class bank
{
int acno;
char nm[100], acctype[100];
float bal;
public:
bank(int acc_no, char *name, char *acc_type, float balance) //Parameterized
Constructor
{
acno=acc_no;
strcpy(nm, name);
strcpy(acctype, acc_type);
bal=balance;
}
void deposit();
void withdraw();
void display();
};
void bank::deposit() //depositing an amount
{
int damt1;
cout<<"\n Enter Deposit Amount = ";
cin>>damt1;
bal+=damt1;
}
void bank::withdraw() //withdrawing an amount
30
{
int wamt1;
cout<<"\n Enter Withdraw Amount = ";
cin>>wamt1;
if(wamt1>bal)
cout<<"\n Cannot Withdraw Amount";
bal-=wamt1;
}
void bank::display() //displaying the details
{
cout<<"\n ----------------------";
cout<<"\n Account No. : "<<acno;
cout<<"\n Name : "<<nm;
cout<<"\n Account Type : "<<acctype;
cout<<"\n Balance : "<<bal;
}
int main()
{
int acc_no;
char name[100], acc_type[100];
float balance;
cout<<"\n Enter Details: \n";
cout<<"-----------------------";
cout<<"\n Accout No. ";
cin>>acc_no;
cout<<"\n Name : ";
cin>>name;
cout<<"\n Account Type : ";
cin>>acc_type;
cout<<"\n Balance : ";
cin>>balance;

bank b1(acc_no, name, acc_type, balance); //object is created


b1.deposit(); //
b1.withdraw(); // calling member functions
b1.display(); //
return 0;
}

Output:

Enter Details:
-----------------------
Accout No. 45612

Name : SHRUTI
31
Account Type : SAVINGS

Balance : 6000

Enter Deposit Amount = 2500

Enter Withdraw Amount = 1000

----------------------
Account No. : 45612
Name : SHRUTI
Account Type : SAVINGS
Balance : 7500

Screenshot:

32
EXPERIMENT NO. 11

AIM: Design a class Vector uses a constructor to initialize the values. Vector class
must perform following functionalities:
 Create a vector  To multiply by a scalar value
 To modify the values of the given  To display the vector
element in vector  Use a destructor also.

Program:

#include<iostream>
#include<stdio.h>
using namespace std;

class vector
{
int size;
int *coord;
public:
vector();
void modify();
void display();
void multiply();
};
vector::vector()
{
cout<<"\n Enter Number of Co-ordinates : ";
cin>>size;
coord=new int[size];
cout<<"\n Enter " << size << " Co-ordinates : \n";
for(int i=0; i<size; i++)
{
cout<<" ";
cin>>coord[i];
}
}
void vector::modify() //Function for Modifying the Co-ordinates
{
cout<<endl<<"\n Enter " << size << " New Co-ordinates : \n";
for(int i=0; i<size; i++)
{
cout<<" ";
cin>>coord[i];
}
33
}
void vector::multiply() //Multiplying the Co-ordinates
{
int num;
cout<<endl<<"\n Enter Number to Multiply : ";
cin>>num;
for(int i=0; i<size; i++)
{
coord[i]=coord[i]*num; //Multiplying the co-ordinates with the number
entered by the user
}
}
void vector::display() //Displaying the vector
{
cout<<"\n Vector : (";
for(int i=0; i<size; i++)
{
cout<<coord[i];
if(i!=size-1)
cout<<",";
}
cout<<")";
}
int main()
{
vector v;
v.display();
v.modify();
v.display();
v.multiply();
v.display();
return 0;
}

Output:

Enter Number of Co-ordinates : 5

Enter 5 Co-ordinates :
20
45
10
17
9

Vector : (20,45,10,17,9)
34
Enter 5 New Co-ordinates :
43
24
11
25
4

Vector : (43,24,11,25,4)

Enter Number to Multiply : 3

Vector : (129,72,33,75,12)

Screenshot:

35
EXPERIMENT NO. 12

AIM: Write a Menu given class in C++ which demonstrate simple constructor,
Parameterized constructor and copy constructor

Program:

DEFAULT CONSTRUCTOR:

#include <iostream>
using namespace std;
class Wall // declare a class
{
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;
}

Output:

Creating a wall.
Length = 5.5

Screenshot:

36
Program:

PARAGIVEN CONSTRUCTOR

#include <iostream>
using namespace std;

class Point
{
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX()
{
return x;
}
int getY()
{
return y;
}
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

return 0;
}

Output:

p1.x = 10, p1.y =


15

37
Screenshot:

Program:

COPY CONSTRUCTOR

#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(const Point &p1) {x = p1.x; y = p1.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}

Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

38
Screenshot:

39
EXPERIMENT NO. 13

AIM: Design a class complex and use friend function to access private data
members of the class

Program:

#include <iostream>
using namespace std;

class Distance
{

private:
int meter;

// friend function
friend int addFive(Distance);

public:
Distance() : meter(0) { }

};

// friend function definition


int addFive(Distance d)
{
//accessing private members from the friend function
d.meter += 5;
return d.meter;
}

int main()

{
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}

Output:

Distance: 5

40
Screenshot:

41
EXPERIMENT NO. 14

AIM: Design two different classes   student and College, make college class as a
friend of student and access private data of class

Program:

#include<iostream>
using namespace std;

class college;
class student
{
public:
student() : s1("SHRUTI"){ }

private:
string s1;
friend void assign(student,college);
};

class college
{
public:
college() : s2("14"){}

private:
string s2;
friend void assign(student,college);
};

void assign(student t,college u)


{
cout<<t.s1<<" is assigned to rollno.: "<<u.s2<<endl;
}

int main()
{
student t;
college u;
assign(t,u);
return 0;
}

42
Output:

SHRUTI is assigned to rollno.: 14

Screenshot:

43
EXPERIMENT NO. 15

AIM: Demonstrate how static data members and member function works with an
example

Program:

//static data member function $ static function member

#include <iostream>
using namespace std;

class Box
{
public:
//static members function
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}

private:
//static data members

double length; // Length of a box


double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;

44
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects.


cout << "Total objects: " << Box::objectCount << endl;
return 0;
}

Output:

Inital Stage Count: 0


Constructor called.
Constructor called.
Final Stage Count: 2

Screenshot:

45
EXPERIMENT NO. 16

AIM: Design a class to overload +,-,* operator

Program:

#include<iostream>
using namespace std;

class Arithmatic
{
float num;
public:
void accept()
{
cout<<"\n Enter Number : ";
cin>>num;
}
Arithmatic operator+(Arithmatic &a)
{
Arithmatic t;
t.num=num+a.num;
return t;
}
Arithmatic operator-(Arithmatic &a)
{
Arithmatic t;
t.num=num-a.num;
return t;
}
Arithmatic operator*(Arithmatic &a)
{
Arithmatic t;
t.num=num*a.num;
return t;
}
Arithmatic operator/(Arithmatic &a)
{
Arithmatic t;
t.num=num/a.num;
return t;
}
void display()
46
{
cout<<num;
}
};
int main()
{
Arithmatic a1, a2, a3;

a1.accept();
a2.accept();
a3=a1+a2;
cout<<"\n --------------------------------------------";
cout<<"\n\n Addition of Two Numbers : ";
a3.display();

a3=a1-a2;
cout<<"\n\n Subtraction of Two Numbers : ";
a3.display();

a3=a1*a2;
cout<<"\n\n Multiplication of Two Numbers : ";
a3.display();

a3=a1/a2;
cout<<"\n\n Division of Two Numbers : ";
a3.display();
return 0;
}

Output:

Enter Number : 23

Enter Number : 73

--------------------------------------------

Addition of Two Numbers : 96

Subtraction of Two Numbers : -50

Multiplication of Two Numbers : 1679

Division of Two Numbers : 0.315068

47
Screenshot:

48
EXPERIMENT NO. 17

AIM: Design a class to overload +++,  -- operators

Program:

#include <iostream>
using namespace std;

class Check
{
private:
int i;
public:
Check(): i(3) { }
Check operator -- ()
{
Check temp;
temp.i = --i;
return temp;
}

// Notice int inside barcket which indicates postfix decrement.


Check operator -- (int)
{
Check temp;
temp.i = i--;
return temp;
}

void Display()
{ cout << "i = "<< i <<endl; }
};

int main()
{
Check obj, obj1;
obj.Display();
obj1.Display();

// Operator function is called, only then value of obj is assigned to obj1


obj1 = --obj;
obj.Display();
49
obj1.Display();

// Assigns value of obj to obj1, only then operator function is called.


obj1 = obj--;
obj.Display();
obj1.Display();

return 0;
}

Output:

i = 3
i = 3
i = 2
i = 2
i = 1
i = 2

Screenshot:

50
EXPERIMENT NO. 18

AIM: Design a class in cpp to convert basic data types to user defined data types

Program:

//conversion from user to basic type


#include<iostream>
using namespace std;
class celsius
{
private:
float temper;
public:
celsius()
{
temper=0;
}
operator float()
{
float fer;
fer=temper *9/5 + 32;
return (fer);
}
void gettemper()
{
cout<<"\n Enter Temperature in Celsius:";
cin>>temper;
}
};
int main()
{
celsius cel; //cel is user defined
float fer; //fer is basic type
cel.gettemper();
fer=cel; //convert from user-defined to basic;
//eqvt to fer= float(cel);
cout<<"\nTemperature in Fahrenheit measurement: "<<fer;
}

Output:

51
Enter Temperature in Celsius:39

Temperature in Fahrenheit measurement: 102.2

Screenshot:

52
EXPERIMENT NO. 19

AIM: Design a class in cpp to convert user defined data types to user defined data
types

Program:

#include<iostream>
#include<cmath>
using namespace std;
class Cartesian
{
private:
float xco, yco;
public:
Cartesian()
{
xco=0;
yco=0;
}
Cartesian(float x, float y)
{
xco=x;
yco=y;
}
void display()
{
cout<<"("<<xco<<","<<yco<<")";
}
};
class Polar
{
private:
float radius, angle;
public:
Polar()
{
radius=0;
angle =0;
}
Polar(float rad, float ang)
{
radius =rad;
53
angle=ang;
}

operator Cartesian()
{
float x=static_cast<int>(radius * cos(angle));
float y=static_cast<int>(radius * sin(angle));
return Cartesian(x,y);
}
void display()
{
cout<<"("<<radius<<","<<angle<<")";
}
};
int main()
{
Polar pol(10.0, 0.78);
Cartesian cart;
cart=pol;
cout<<"\nGiven Polar: ";
pol.display();
cout<<"\nEquivalent cartesian: ";
cart.display();
return 0;
}

Output:

Given Polar: (10,0.78)


Equivalent cartesian: (7,7)

Screenshot:

54
EXPERIMENT NO. 20

AIM: Design a class in cpp to convert user defined data types to basic  data types

Program:

#include <iostream>
using namespace std;
const float MeterToFloat=3.280833;
// Meter to feet
class Distance
{
int feet;
float inches;
public:
Distance() // Default Constructor
{
feet=0;
inches=0.0;
}
Distance(int ft, float in) //two arguements constructor
{
feet=ft;
inches=in;
}
operator float() //overloaded casting operator
{
float feetinfractions=inches/12;
feetinfractions+=float(feet);
return (feetinfractions/MeterToFloat);
}
};
int main()
{
int feet;
float inches;
cout <<"Enter distance in Feet and Inches.";
cout<<"\nFeet:";
cin>>feet;
cout<<"Inches:";
cin>>inches;
Distance dist(feet, inches);
float meters=dist;
55
// This will call overloaded casting operator
cout<<"Converted Distance in Meters is: "<< meters;
}

Output:

Enter distance in Feet and Inches.


Feet:5.2
Inches:Converted Distance in Meters is: 1.52908

Screenshot:

56
EXPERIMENT NO. 21

AIM: Design a class in cpp for Inheritance such that Class student is a base class
having all the basic attributes and functionality. Now derive a new class General
Secretary, add some more attributes and operations to the class

Program:

#include <iostream>
using namespace std;

class Student
{
char name[100];
int age;
char qualification[100];

public:
void getdata()
{
cout << "Name: ";
cin >> name;
cout << "Age: ";
cin >> age;
cout << "Qualification: ";
cin >> qualification;
}
void display()
{
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Qualification: " << qualification << endl;
}
};

class GenSec : public Student


{
char specialization[100];
public:
void getdata()
{
Student::getdata();
cout << "Specialization: ";
cin >> specialization;
57
}
void display()
{
Student::display();
cout << "Specialization: " << specialization << endl;
}
};

int main()
{
Student s;
GenSec g;
cout<<"Student"<<endl;
cout<<"\nEnter Details:"<<endl;
s.getdata();
cout<<endl<<"\nDisplaying Student Details:"<<endl;
s.display();
cout<<"\n-------------------------------------------------- \n";
cout<<endl<<"\nGeneral Secretary"<<endl;
cout<<"Enter Details:"<<endl;
g.getdata();
cout<<endl<<"\nDisplaying Details:"<<endl;
g.display();
return 0;
}

Output:

Student

Enter Details:
Name: SHRUTI
Age: 20
Qualification: BTECH

Displaying Student Details:


Name: SHRUTI
Age: 20
Qualification: BTECH

--------------------------------------------------

General Secretary
Enter Details:
58
Name: ARYA
Age: 21
Qualification: BTECH
Specialization: COMPUTER

Displaying Details:
Name: ARYA
Age: 21
Qualification: BTECH
Specialization: COMPUTER

Screenshot:

59
EXPERIMENT NO. 22

AIM: write a program to implement virtual base class class name: Teacher teacher
having attributes name,qualification and salary. From teacher class two classes are
derived
1. professor 
2. visiting professor 
professor having attribute: subject,semester and department whereas visiting
faculty having attributes: subject, renumeration per hour, time. From professor and
visiting professor a new class is derieved name as instructor. The attributes of the
instructors are: expertise in, conducting the workshop.

Program:

#include <bits/stdc++.h>
using namespace std;

class Teacher
{
public:
string name;
string qualification;

void getData1(){
cout << "Name: ";
cin >> name;
cout << "Qualification: ";
cin >> qualification;
}
void display1(){
cout << "Name: " << name << endl;
cout << "Qualification: " << qualification << endl;
}
};
class Professor: public virtual Teacher
{
public:
string semester;

void getData2(){
getData1();
cout << "Semester: ";
cin >> semester;
}
60
void display2(){
display1();
cout << "Semester: " << semester << endl;
}
};
class VisitingProf: public virtual Teacher
{
public:
string timeslot;

void getData3(){

cout << "Time slot: ";


cin >> timeslot;
}
void display3(){

cout << "Time slot: " << timeslot << endl;


}

};
class Instructor: public Professor, public VisitingProf
{
public:
string expertise;
string renumeration;

void getData4(){
cout << "Expertise: ";
cin >> expertise;
cout << "Renumeration: ";
cin >> renumeration;
cout<<"\n-------------------------------------------------- \n";
}
void display4(){
cout << "Expertise: " << expertise << endl;
cout << "Renumeration: " << renumeration << " per hour" << endl;
cout<<"\n-------------------------------------------------- \n";
}
};
int main(){
Instructor p1;
p1.getData2();
p1.getData3();
p1.getData4();
p1.display2();
p1.display3();
p1.display4();
61
return 0;
}

Output:

Name: SHRUTI
Qualification: BTECH
Semester: 5
Time slot: 40_HOURS
Expertise: OBJECT_ORIENTED_PROGRAMMING
Renumeration: 2000

--------------------------------------------------
Name: SHRUTI
Qualification: BTECH
Semester: 5
Time slot: 40_HOURS
Expertise: OBJECT_ORIENTED_PROGRAMMING
Renumeration: 2000 per hour

--------------------------------------------------

Screenshot:

62
EXPERIMENT NO. 23

AIM: Demonstrate the use of virtual base class

Program:

#include<iostream>

using namespace std;

class student
{
protected: int roll_no;

public: void get_no(int x)


{
roll_no=x;
}

void put_no()
{
cout<<"Roll Number:"<<roll_no;
}
};

class test: virtual public student


{
protected: float sub_marks;

public: void get_submarks(float y)


{
sub_marks=y;
}

void put_submarks()
{
cout<<"\nSubject Marks:"<<sub_marks;
}
};

class sports: public virtual student


{
protected: float sp_marks;

public: void get_spmarks(float z)


63
{
sp_marks=z;
}

void put_spmarks()
{
cout<<"\nSports Marks:"<<sp_marks;
}
};

class result: public test, public sports


{
float total_marks;

public: void put_result()


{
total_marks=sub_marks+sp_marks;
put_no();
put_submarks();
put_spmarks();
cout<<"\nTotal Marks:"<<total_marks;
}
};

int main()
{
result R;

R.get_no(20);
R.get_submarks(75.6);
R.get_spmarks(81.2);
R.put_result();
return 0;
}

Output:

Roll Number:20
Subject Marks:75.6
Sports Marks:81.2
Total Marks:156.8

Screenshot:

64
65
EXPERIMENT NO. 24

AIM: Design a abstract class in cpp and make practically impossible to instantiate
the class

Program:

#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}

Output:

fun() called

Screenshot:

66
EXPERIMENT NO. 25

AIM: Prove that CPP is a robust language using exception handling mechanisms and
handle at least any 3 exceptions in one program

Program:

#include <iostream>
#include<conio.h>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main()
{
int m = 50;
int s = 0;
double z = 0;
try {
z = division(m, s);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}

int x[3] = {-1,2};


for(int i=0; i<2; i++)
{
int ex = x[i];
try
{
if (ex > 0)
// throwing numeric value as exception
throw ex;
else
// throwing a character as exception
throw ex;
}
catch (int ex) // to catch numeric exceptions
{
cout << "Integer exception\n";

67
}

catch (char ex) // to catch character/string exceptions


{
cout << "Character exception\n";
}
}
}

Output:

Division by zero condition!


Integer exception
Integer exception

Screenshot:

68
EXPERIMENT NO. 26

AIM: Design a class in cpp to operate on string

Program:

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

// Custom string class


class Mystring {

// Initialise the char array


char* str;
public:
// No arguments Constructor
Mystring();

// Constructor with 1 arguments


Mystring(char* val);

// Copy Constructor
Mystring(const Mystring& source);

// Move Constructor
Mystring(Mystring&& source);

// Destructor
~Mystring() { delete str; }
};

// Function to illustrate Constructor


// with no arguments
Mystring::Mystring()
: str{ nullptr }
{
str = new char[1];
str[0] = '\0';
}

// Function to illustrate Constructor


// with one arguments
Mystring::Mystring(char* val)
69
{
if (val == nullptr) {
str = new char[1];
str[0] = '\0';
}
else {
str = new char[strlen(val) + 1];
// Copy character of val[]
// using strcpy
strcpy(str, val);
str[strlen(val)] = '\0';
cout << "The string passed is: "
<< str << endl;
}
}

// Function to illustrate
// Copy Constructor
Mystring::Mystring(const Mystring& source)
{
str = new char[strlen(source.str) + 1];
strcpy(str, source.str);
str[strlen(source.str)] = '\0';
}

// Function to illustrate
// Move Constructor
Mystring::Mystring(Mystring&& source)
{
str = source.str;
source.str = nullptr;
}

// Driver Code
int main()
{
// Constructor with no arguments
Mystring a;

// Convert string literal to


// char array
char temp[] = "Hello";

// Constructor with one argument


Mystring b{ temp };

// Copy constructor
70
Mystring c{ a };
char temp1[] = "World";

// One arg constructor called,


// then the move constructor
Mystring d{ Mystring{ temp } };
return 0;
}

Output:

The string passed is: Hello


The string passed is: Hello

Screenshot:

71
EXPERIMENT NO. 27

AIM: Copy string, concatenate the string, delete string, convert lower case to upper
case, size of the string

Program:

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

int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

// lowercase to uppercase
for (int i =0; i < str3.length(); i++)
{
str3[i] = toupper(str3[i]);
}
cout << "str3 :" << str3 << endl;

// delete string
str3.erase();
cout << "str3 : " << endl;
return 0;
}

72
Output:

str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
str3 :HELLOWORLD
str3 :

Screenshot:

73
EXPERIMENT NO. 28

AIM: Design a class in cpp to create a new file, modify the file and save the
content of the file

Program:

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

char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
74
}

Output:

Writing to the file


Enter your name: SHRUTI_MANOJ_CHAVAN
Enter your age: 20

Reading from the file


SHRUTI_MANOJ_CHAVAN
20

Screenshot:

75

You might also like