Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ constructor question

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);
like image 684
Simplicity Avatar asked Feb 14 '11 09:02

Simplicity


2 Answers

Generally you should prefer the first construct, i.e. using the initialiser list.

The second construct is preferable if

  1. you wish to put a try..catch around it or
  2. You have several of these and are going to store them as regular pointers, in which case you need to beware that one of your news might fail and you will need to do some cleanup. You would handle this by using some kind of auto_ptr / unique_ptr until you know all the allocations have succeeded, then go around releasing them. This is because you presumably delete them in your destructor, but your destructor will not get called if the constructor throws.
like image 76
CashCow Avatar answered Sep 30 '22 00:09

CashCow


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?

  1. If 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.
  2. When 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.

like image 22
Marcelo Cantos Avatar answered Sep 30 '22 00:09

Marcelo Cantos