Bahria University, Lahore Campus: Department of Computer Science
Bahria University, Lahore Campus: Department of Computer Science
Objective(s):
Upon completion of this lab session, learners will be able to:
Composition and Aggregation relation between classes
Lab Tasks:
Task 1
Create a class Distance having a member meter. Now create a friend function named
convert() that increments meter by 5 and then converts that meter in kilo meters and return
the answer. Call the function in main.
Code:
#include<iostream>
#include<string>
using namespace std;
class Distance
{
double metre;
public:
Distance(double d) :metre(d)
{}
friend double convert(Distance);
};
double convert(Distance d)
{
d.metre += 5;
d.metre /= 1000;
return d.metre;
}
int main()
{
double x;
cout << "Enter distance in metres: ";
cin >> x;
Distance d(x);
//Distance d(495);
cout << "Converted Distance in Kilometres= " << convert(d) << endl;
system("pause");
return 0;
}
%
Enrollment Number: ____________________________
Task 2
Implement the classes according to the given class diagram. It shows both the composition
and aggregation relationships.
Code:
#include<iostream>
#include<string>
using namespace std;
class Engine
{
int n;
public:
Engine(int a) :n(a)
{
cout << "Engine Constructor" << endl;
}
~Engine()
{
cout << "Engine Destructor" << endl;
}
void showengine()
{
cout << "Engine Number=" << n << endl;
};
class Driver
{
string name;
int age;
public:
Driver(string n = "", int a = 0) :name(n), age(a)
{
cout << "Driver Constructor" << endl;
}
~Driver()
{
cout << "Driver Destructor" << endl;
}
void showdriver()
{
cout << "Name:" << name << endl;
cout << "Age:" << age << endl;
}
};
class Vehicle
{
Page 2 of 3
%
Enrollment Number: ____________________________
private:
string company;
Driver *d;
string color;
public:
Vehicle(string a, string b, Driver *c) :d(c), company(a), color(b)
{
cout << "Vehicles Constructor" << endl;
}
void showvehicle()
{
cout << "Company=" << company<< endl;
cout << "Color=" << color << endl;
d->showdriver();
}
~Vehicle()
{
cout << "Vehicles Destructor" << endl;
}
};
int main()
{
Driver d("Fasih Waseem", 19);
Vehicle v("Vigo", "Black", &d);
Engine e(3332);
v.showvehicle();
e.showengine();
system("pause");
return 0;
}
Note : Attempt all tasks and get them checked by your Lab Instructor.
Page 3 of 3