In the C++ programming for the absolute Beginner, 2nd edition book, there was the following statement:
HeapPoint::HeapPoint(int x, int y): thePoint(new Point(x,y)) { }
Is this equal to:
HeapPoint::HeapPoint(int x, int y) { thePoint = new Point(x,y); }
And, since we are doing this in a constructor, what are the values assigned for x
and y
? Should we write values insted of x
and y
in new Point(x,y)
? Or, it is correct that way?
UPDATE: I think I got the idea of initializing x
and y
, as in the book it has the following in a function:
HeapPoint myHeapPoint(2,4);
Generally you should prefer the first construct, i.e. using the initialiser list.
The second construct is preferable if
Assuming thePoint
is a raw pointer, it is, for all intents and purposes, the same. The first version initialises thePoint
, whereas the second assigns to it, but the effect is almost always the same, even to the point of generating exactly the same machine code.
When aren't they the same?
thePoint
is some kind of smart pointer, the first form will initialise it by passing the new Point to its constructor, whereas the second form will probably zero-initialise it and then pass the new Point to its assignment operator.thePoint
is one of several member variables, the first form will initialise it in the order it appears in the class definition, whereas the second form will assign in the body of the constructor. So the order in which things get "hydrated" may vary between the two forms, which may matter if some members variables depend on others.If you are a beginner, most of this is probably meaningless to you. But don't worry about it. These differences are very subtle and will almost never matter. (I'm sure there are other exceptions, but none come to mind just now.)
It's ultimately a matter of style and consistency, for which I prefer the initialisation form over the assignment form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With