order of precedence

Jul 24, 2013 at 3:29am
if I have:
Cars car1 = car2 + car3;

the + operator is overload to return a Cars object.
When this is call...what happens first ? It looks like my code is trying to create a car1 object first, because it errors with 'no matching function'.


Thanks

Jul 24, 2013 at 3:39am
it errors with 'no matching function'

Your overloaded + function is probably not correct.
Can't tell for sure without seeing your class declaration.
Jul 24, 2013 at 5:04am
it works like this: Cars car1; car1 = car2 + car3;
but not Cars car1 = car2 + car3;
Jul 24, 2013 at 7:02am
http://www.cplusplus.com/doc/tutorial/operators/

On the very end of this site you have a table answering your question.
Jul 24, 2013 at 10:45am
Cars car1 = car2 + car3;

Although it's using the '=' character, this is actually an initialisation, so it's the same as:

 
Cars car1(car2 + car3);


Assuming car2 and car3 are of type Cars, then the result of car2 + car3 should be of type Cars. This means that car1 is created using the copy constructor of Cars.

Have you written a copy constructor for Cars?
Last edited on Jul 24, 2013 at 10:45am
Jul 24, 2013 at 11:10am
nmn wrote:
When this is call...what happens first ? It looks like my code is trying to create a car1 object first, because it errors with 'no matching function'.

The order the code is compiled doesn't necessary have anything to do with the order in which things happen at runtime.

MikeyBoy gave the correct explanation of why you get the error you do.
Jul 25, 2013 at 4:32am
thanks all...great stuff.
Jul 25, 2013 at 3:43pm
How in the world do you prototype this copy constructor ?

Cars car1(car2 + car3);
Jul 25, 2013 at 3:47pm
There is only 1 way to prototype any copy constructor because there is only 1 copy constructor:

 
Cars( const Cars& car_to_copy );
Jul 25, 2013 at 3:53pm
OK... i think i see it. the (car2 + car3) gets evaluated first, then the reference of this result is used. Right ?
Jul 25, 2013 at 4:03pm
correct.
Topic archived. No new replies allowed.