Constructor Definition C++ syntax [duplicate]

  • A+

This question already has an answer here:

What's the difference between these two declarations of constructors:

class Fruit {   private:     int price;    public:     Fruit(int x): price(x)     {     }     }; 


class Fruit {   private:     int price;    public:     Fruit(int x)     {         price = x;     } }; 

The first one I have seen in case of inheritance.

As per my knowledge, this is not a duplicate question. If you find one feel free to close this question.


The first one initialize price with x where the second one initialize price with its default value (default construct it; in case of a int variable, is initialized with an undefined value) and then copy x in price.

In other words, the first one is almost equivalent to

int price = x; 

where the second one is almost equivalent to

int price;  price = x; 

In case of a int variable (taking also in count the compiler's optimizations) I suppose there isn't an effective difference.

But when price is a complex object, with an heavy construction cost, there can be a great difference.

As explain Peter, "It's not construction cost that makes the difference between the two for complex objects. It is a question of whether reassigning after default initialisation is more costly than initialising in one step. Practically, the two stage process is often more expensive (by various measures) than direct initialisation, since it can be necessary to clean up the default setting in order to change the value. There are also concerns of exception safety - what if reassignment or construction throws an exception."

So, usually, is strongly suggested to use the first solution (initialize the object with the right value).

See also the Zereges's answer that point the attention over the fact that the first one method is the only available to assign a value to a constant member.

Indeed you can't write

int const  price;  price = x;  // error: price is const 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: