General discussion

Locked

Please help!

By Foe ·
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.

This conversation is currently closed to new comments.

1 total post (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

here's how

by John Torjo In reply to Please help!

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

Back to Web Development Forum
1 total post (Page 1 of 1)  

Related Discussions

Related Forums