passing an object to another object from another class

First, you need to make your getAmount() function virtual:

class Cargo{
public:
    double c = 0;
    virtual double getAmount(){
        return c;
    }
};

Then, your derived classes will override the getAmount() function with their version.

Without the virtual keyword, if your function accepts a parameter of type Cargo, it will just used the Cargo::getAmount() function.

Second, you need to pass your object into by const-reference, like this:

class Truck {
    double maxCapacity = 8;
public:
    void loadCargo(const Cargo& cargo){
        maxCapacity = maxCapacity - cargo.getAmount();
    }
    ...

This will ensure that your cargo object inside the loadCargo function will refer to an Apple object or a Kiwi object. By passing by value, you’re copying your Apples object into a Cargo object, and you fall over the slicing problem.

ETA: You would also need to change your getAmount() function to const like this:

//                 vvvvv
double getAmount() const {
    return c;
}

Since you mention you cannot change your Truck class, you can do this by setting the value of c in your Cargo class constructor. Like this:

class Cargo{
public:
    double c;

    // Constructor, using an initializer list to set the value of `c`.
    Cargo(const double c_value) :
        c(c_value) {
    }

    double getAmount(){
        return c;
    }
};

Then, in your Apple and Kiwi classes, set the value of c inside the constructor, like this:

class Apple : public Cargo{
public:
    // Set the Cargo's mass in the Apple constructor...
    Apple() :
        Cargo(1.5) {
    }

    // getAmount() function removed.
};

Finally, remove the getAmount() functions from your Apple and Kiwi classes (but KEEP for the Cargo class).

Final Note

Please bear in mind that passing Cargo by value will always suffer from the Slicing Problem (see link above) and should be avoided, though because your Apple and Kiwi objects don’t have any member variables, it will still work for your assignment. If inheritance is how your instructor wanted this to work, then passing Cargo by value into loadCargo(Cargo cargo) is bad C++ practice. This doesn’t impact your assignment, but if you wish to take C++ seriously, bear this in mind for the future!

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top