Discussion Locked

Please help!

0 helpful
1 reply
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have just started uni and I am doing c++. My question is how do you pass or add an object of one type to another class? For example suppose you have two classes, 1 - a Vehicle class, and 2 - a FuelPurchase class. In the driver program I want to beable to add FuelPurchase to Vehicle by overloading the + operator in the Vehicle class e.g.

int main(){
Vehicle a("Manufacturer","Holden",2003");
a = a + FuelPurchase(100,70);
return 0;
}

Well that is my question (I hope that I explained my problem enough), if any one could help me out it would be much appreciated.

1 reply

by john torjo

Hi,

First, let me tell you there are other ways to do what you want, like:

a.addFuelPurchase( FuelPurchase( 100, 70));

Anyway, you can overload operator +, like this:

// (non-member function)
Vehicle & operator+( const Vehicle & v, const FuelPurchase & purchase)
{
// whatever.
}

It would be even simpler to have an overloaded operator +=, which would allow you to do:
a += FuelPurchase(...);

// member function of Vehicle class
Vehicle & operator +=( const FuelPurchase & purchase)
{
// your implementation
return *this;
}

Hope this helps.

Best,
John

This discussion is closed to new replies.