Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the name and reason for member variable assignment between function name and curly braces?

Look at this code snippet:

Size::Size(int iSetWidth, int iSetHeight)
:iWidth(iSetWidth),
iHeight(iSetHeight)
{
}

Supposedly, this means the same thing as:

Size::Size(int iSetWidth, int iSetHeight)
{
    iWidth=iSetWidth;
    iHeight=iSetHeight;
}

Why would you use the former or the latter? And what is the name of the former?

like image 507
bastibe Avatar asked Sep 02 '10 10:09

bastibe


2 Answers

No, they don't mean exactly the same.

When a constructor is executed, before entering the code block (the code between the curly braces), it constructs all object data members. What you do in the initializers (the code after the colon and before the curly braces) is to specify which constructors to use for those members. If you don't specify a constructor for a specific data member, the default constructor will be used.

So, if you use the initialization list (first example), the right constructors will be used for each member and no additional code is necessary. If you don't, first the default constructor is used and then the code inside the curly braces is executed.

In summary:

  1. In your first example, each member is initialised using the appropriate constructor, probably the copy constructor.
  2. In your second example, each member is constructed using the default constructor, and then some additional code is executed to initialise it, probably the assignment operator.

EDIT: Sorry, forgot to answer your questions in the last line.

The name of the code between the colon and the curly braces is initialisation list.

If you know which is the right constructor for a variable or data member, by all means use it. This is the reason why most classes have different constructors instead of just a default constructor. So you are better off using the initialization list.

The initialisation list is almost never slower than the other technique, and can easily be faster. A well known rule when writing code is "don't optimize prematurely", but there is a not so well known counterpart: don't pessimize prematurely. If you have two options for writing a piece of code and one of them can be better than the other, but does not involve additional work or complexity, use it. In your example there is no difference, since you are using a built-in type (int). But if you were using classes, there would be a difference, so get used to the initialization list.

like image 108
Gorpik Avatar answered Oct 16 '22 10:10

Gorpik


THe former is called initilazation lists. You can get plentyof articles for that.

The particular reasons for using intializer lists are given here http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/

You can refer Effective C++ to get full insight into intializer lists. Hope it is clear.

like image 32
ckv Avatar answered Oct 16 '22 10:10

ckv