Write the OOP components such that a user can create Transportation objects. We
ID: 3582349 • Letter: W
Question
Write the OOP components such that a user can create Transportation objects. We will implement both a Car and a Train. Each Transportation object will have a speed in member variable that will be passed to the constructor. Each Transportation object will keep track of how far it has traveled. Each class will implement a Go(x) member function that will drive the Transportation object for x time steps and then return the total distance the Transportation object has traveled in total. The Transportation class can simply return 0 for this function. We can assume each Transportation object starts at 0 distance traveled. (Exact units do not matter for this question. Assume speed is some distance over a unit time and that the value returned by Go(x) is of the same unit as the speed unit.)Explanation / Answer
// This is c++ code for given question. place the code in a file "filename.cpp"
// you need to compile the code by following command "g++ filename.cpp"
// and then run the executable using following command "./a.out"
#include <bits/stdc++.h>
using namespace std;
class train
{
public:
int speed;
int total_distance;
train(int speed);
int Go(int x);
};
train::train(int my_speed)
{
speed = my_speed;
total_distance = 0;
}
int train::Go(int x)
{
total_distance = total_distance + x;
return total_distance;
}
class car
{
public:
int speed;
int total_distance;
car(int speed);
int Go(int x);
};
car::car(int my_speed)
{
speed = my_speed;
total_distance = 0;
}
int car::Go(int x)
{
total_distance = total_distance + x;
return total_distance;
}
int main()
{
train train1(1); // declaired object of class train with speed 1
train train2(2); // declaired object of class train with speed 2
train1.Go(5);
train1.Go(5);
train1.Go(5);
train2.Go(5);
train2.Go(5);
cout << "speed "<< train1.speed << " total_distance "<< train1.total_distance << endl;
cout << "speed "<< train2.speed << " total_distance "<< train2.total_distance << endl;
car car1(3); // declaired object of class car with speed 3
car car2(4); // declaired object of class car with speed 4
car1.Go(50);
car1.Go(50);
car1.Go(50);
car2.Go(50);
car2.Go(50);
cout << "speed "<< car1.speed << " total_distance "<< car1.total_distance << endl;
cout << "speed "<< car2.speed << " total_distance "<< car2.total_distance << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.