I am trying to write this program using base classes and derived classes where there is a truck with a maximum capacity of 8 tons. Then this truck is loaded with 1.5 tons of apple and then loaded with 0.5 tons of kiwi. This would then diminish the amount of tons remaining to 6.5 when the apples are loaded and then to 6 when the kiwis are loaded. This is an assignment and in the main function I see they are calling the function loadCargo
as follows truck.loadCargo(Apple())
, I am unsure of what this is accomplishing. Please take a look at the complete code:
#include <iostream>
#include <string>
using namespace std;
class Cargo{
public:
double c = 0;
double getAmount(){
return c;
}
};
class Apple : public Cargo{
public:
double c = 1.5;
double getAmount(){
return c;
}
};
class Kiwi : public Cargo{
public:
double c = 0.5;
double getAmount(){
return c;
}
};
class Truck {
double maxCapacity = 8;
public:
void loadCargo(Cargo cargo){
maxCapacity = maxCapacity - cargo.getAmount();
}
void printInfo(){
cout << maxCapacity << " tons remaining" << endl;
}
};
int main() {
Truck truck;
truck.printInfo();
truck.loadCargo(Apple());
truck.printInfo();
truck.loadCargo(Kiwi());
truck.printInfo();
}
I thought that truck.loadCargo(Apple())
would pass an object of Apple to the object cargo. Therefore when loadCargo
is called, it would access the getAmount
function in Apple class and not in class Cargo but that is not happening. The output should be:
8 tons remaining
6.5 tons remaining
6 tons remaining
But currently it is the following since it just using the getAmount
from the Cargo class:
8 tons remaining
8 tons remaining
8 tons remaining
EDIT: Since this is an assignment I cannot change anything in the main function or in the line that has void loadCargo(Cargo cargo)
.