Oop 9
Oop 9
Section: A
Semester: 2nd
1. Write a program that has a class to represent time. The class
should have constructors initialize data members hour, minute and
second to 0 and to initialize them to values passes as arguments. The
class should have member function to add time objects and return the
result as time object. There should be another function to display the
result in 24 hour format.
Ans:
#include<iostream>
using namespace std;
class time
{
private:
int hh,m,s;
public:
time add(time);
void display();
time()
{
hh=0;
m=0;
s=0;
}
time(int a,int b,int c)
{
hh=a;
m=b;
s=c;
}
};
time time::add(time y)
{
time x;
x.s=s+y.s;
x.m=x.s/60;
x.s=x.s%60;
x.m=x.m+m+y.m;
x.hh=x.m/60;
x.m=x.m%60;
x.hh=x.hh+hh+y.hh;
return x;
}
void time::display()
{
cout<<hh<<" hour "<<m<<" minutes and "<<s<<" seconds"<<endl;
}
int main()
{
time t1,t2(10,30,05),t3(8,50,36),t4;
cout<<"\nFirst time is\n";
t1.display();
cout<<"\nSecond time is\n";
t2.display();
cout<<"\nThird time is\n";
t3.display();
t4=t2.add(t3);
cout<<"\nTime after addition is\n";
t4.display();
return 0;
}
Ans:
#include<iostream>
using namespace std;
class vechicle
{
private:
int num_vechicle,h;
float r,c;
public:
vechicle(int x,int y,float z)
{
num_vechicle=x;
h=y;
r=z;
}
void display()
{
if(num_vechicle>10)
{
c=h*r;
c=c-((float(10)/100)*c);
cout<<"Charge is "<<c<<endl;
}
else
{
c=h*r;
cout<<"Charge is "<<c<<endl;
}
}
vechicle(vechicle &v2)
{
num_vechicle=v2.num_vechicle;
h=v2.h;
r=v2.r;
}
};
int main()
{
vechicle v1(10,12,700);
v1.display();
vechicle v3=v1;
v3.display();
return 0;
}
3. Write a class that can store Department ID and Department Name
with constructors to initialize its members. Write destructor member
in the same class and display the message”. Object n goes out of
scope”. Your program should be made such that it should show the
order of constructor and destructor invocation.
Ans:
#include<iostream>
#include<cstring>
using namespace std;
class department
{
private:
int id;
string na;
public:
department(int i,string n)
{
id=i;
na=n;
cout<<"object "<<id<<" is created with name "<<na<<endl;
}
~department()
{
cout<<"object "<<id<<" goes out of scope"<<endl;
}
};
int main()
{
department d1(1,"Kaushaltar department ");
department d2(2,"lokanthali department ");
return 0;
}
Output: