C++: Where to initialize variables in constructor [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ initialization lists
What are the pros/cons of initializing variables at option 1 vs option 2?
class MyClass
{
public:
MyClass( float f, char a );
private:
float mFloat;
char mCharacter;
bool mBoolean;
int mInteger;
};
MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ) // option 1.
{
// option 2
mCharacter = a;
mInteger = 0;
}
Edit:
Why is option 2 so common?

In short, always prefer initialization lists when possible. 2 reasons:
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.
Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.
Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.

Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.

See Should my constructors use "initialization lists" or "assignment"?
Briefly: in your specific case, it does not change anything. But:
for class/struct members with constructors, it may be more efficient to use option 1.
only option 1 allows you to initialize reference members.
only option 1 allows you to initialize const members
only option 1 allows you to initialize base classes using their constructor
only option 2 allows you to initialize array or structs that do not have a constructor.
My guess for why option 2 is more common is that option 1 is not well-known, neither are its advantages. Option 2's syntax feels more natural to the new C++ programmer.

Option 1 allows you to use a place specified exactly for explicitly initializing member variables.

Option 1 allows you to initialize const members. This cannot be done with option 2 (as they are assigned to, not initialized).
Why must const members be intialized in the constructor initializer rather than in its body?

There are many other reasons. You should always initialize all member variables in the initialization list if possible.
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

Related

Default struct initialisation in any case?

I realized that in C++ you can initialize any structure with default values. I don't think that was possible under C. Is that correct?
Are there situations in which it still makes sense not to use such a default initialization? Or is it better in any case since it is safer?
I also saw that there are different ways to do this.
Is One Method Better Than Another? Or is it just a matter of taste?
struct STR_Foo {
int value{ 0 };
};
struct STR_Foo {
int value = 0;
};
struct STR_Foo {
int value = { 0 };
};
I realized that in C++ you can initialize any structure with default values. I don't think that was possible under C. Is that correct?
Yes.
Are there situations in which it still makes sense not to use such a default initialization?
If you target Older standard than C++11 - or cross-compatibility with C. Default member initialisers weren't in the language before that - and aren't in C.
If you target C++11 standard and you want the class to be an aggregate. Since C++14 default member initialisers don't disqualify a class from being an aggregate.
If you need an instance of the class to be initialised later and have measured that you cannot afford the very low overhead of redundant initialisation.
I also saw that there are different ways to do this. Is One Method Better Than Another? Or is it just a matter of taste?
The choice to use = or not is stylistic when using curly brackets. Attempting to initialise without = and parentheses instead of curlies ends up being a function declaration for some cases, so you need to disambiguate by using = or curlies.
Curly brackets affect the form of initialisation in some cases. In cases where curlies and no curlies invoke the same constructor, using curlies is recommended because that syntax don't allow narrowing conversions. When curlies invoke a different constructor than no curlies, use the form that does what you need.
These apply to all initialisation; not just default members.

C++ constructor syntax and zero-initialization

This is a short question about syntax in c++:
class arrayInit {
public:
bool vars[2];
arrayInit() : vars() {} //1
};
class array {
public:
bool vars[2];
array() {} //2
};
What does 1 and 2 do?
Why they don't zero initialize like this: bool vars[2]={};?
What is the purpose of arrayInit() : and array()? and what is it called so I could search for it?
It's from: https://msujaws.wordpress.com/2010/06/16/initializing-an-array-in-c/
What does 1 and 2 do?
Both 1 and 2 define the default constructor for the respective type
Why they don't zero initialize like this: bool vars[2]={};?
They could if they were using a compiler with c++11 support. Also var() will value initialize the array which is same as vars[2] = {} will explicitly initialize all elements to false
What is the purpose of arrayInit() : and array()? and what is it
called so I could search for it?
They are called the default constructors. C++ compiler will create them for you unless you want to do something special in them. If you were mentioning about what is written beyond the : (colon), that expression is called the initializer list
Read more here
What does 1 and 2 do?
Both allow you to override the default initialization for an array.
InitArray is specifically initializing the vars array with no parameters, I believe it will assume 0 as the default parameter.
Array is not specifically initializing the array, so it is falling back to a default initialization case.
Why they don't zero initialize like this: bool vars[2]={};?
You could do this, this is just another option which encapsulates the bool array in a class to allow you to provide other functionality if you wish.
What is the purpose of arrayInit() : and array()?
If you want default functionality, there is no need to encapsulate the array in its own class. Encapsulation allows you to encapsulate a type to provide different functionality from the default, you could go on to add methods for addition, subtraction, or anything you can think up and have it perform the methods in the way that you specify.
and what is it called so I could search for it?
Good question; Encapsulation, class initialization, array initialization.
http://www.cplusplus.com/doc/tutorial/classes/
Both arrayInit() and array() are default constructors. If the default constructor is missing and other constructors are available, you cannot declare an object from that class type without calling the other constructors e.g. you cannot do this arrayInit arr; without the default constructor.
The part : vars() is called the initialization list. You can read more about them in this link: http://en.cppreference.com/w/cpp/language/initializer_list

How to define a Struct with default values?

Rather surprised to find this question not asked before. Actually, it has been asked before but the questions are VERY DIFFERENT to mine. They are too complicated and absurd while I'll keep it simple and to the point. That is why this question warrants to be posted.
Now, when I do this,
struct A {
int a = -1;
};
I get the following error:
ANSI C++ forbids in-class initialization of non-const static member a
Now, along with the workaround can someone please tell me THE BEST way of initializing a struct member variable with a default value?
First, let's look at the error:
ANSI C++ forbids in-class initialization of non-const static member a
Initialization of a true instance member, which resides within the memory of an instance of your struct is the responsibility of this struct's constructor.
A static member, though defined inside the definition of a particular class/struct type, does not actually reside as a member of any instances of this particular type. Hence, it's not subject to explaining which value to assign it in a constructor body. It makes sense, we don't need any instances of this type for the static member to be well-initialized.
Normally, people write member initialization in the constructor like this:
struct SomeType
{
int i;
SomeType()
{
i = 1;
}
}
But this is actually not initialization, but assignment. By the time you enter the body of the constructor, what you've done is default-initialize members. In the case of a fundamental type like an int, "default-initialization" basically boils down to "eh, just use whatever value was in those bytes I gave you."
What happens next is that you ask i to now adopt the value 1 via the assignment operator. For a trivial class like this, the difference is imperceptible. But when you have const members (which obviously cannot be tramped over with a new value by the time they are built), and more complex members which cannot be default-initialized (because they don't make available a visible constructor with zero parameters), you'll soon discover you cannot get the code to compile.
The correct way is:
struct SomeType
{
int i;
SomeType() : i(1)
{
}
}
This way you get members to be initialized rather than assigned to. You can initialize more than one by comma-separating them. One word of caution, they're initialized in the order of declaration inside your struct, not how you order them in this expression.
Sometimes you may see members initialized with braces (something like i{1} rather i(c)). The differences can be subtle, most of the time it's the same, and current revisions of the Standard are trying to smooth out some wrinkles. But that is all outside the scope of this question.
Update:
Bear in mind that what you're attempting to write is now valid C++ code, and has been since ratification of C++11. The feature is called "Non-static data member initializers", and I suspect you're using some version of Visual Studio, which still lists support as "Partial" for this particular feature. Think of it as a short-hand form of the member initialization syntax I described before, automatically inserted in any constructor you declare for this particular type.
You could make a default constructor
struct A {
A() : a{-1} {}
int a;
};

c++ default argument vs. initalizer list

There are four specific cases , where you must specify default initializer list.
Fully discussed here
In short, if you have
Initializer list Required
non-static const data members
data member of reference type
provide params to data members which are objects of other class
provide base class ctor parameters from derived class.
The one drawback to default argument seems to be that the default arguments must be the trailing parameters in the function prototype parameter list. For example:
drawbacks(???) to default arguments
void f(int, int = 2, int = 3); // trailing defaults
void g(int = 1, int = 2, int c); // error
void h(int, int = 3, int); // error
My question is, if my code does not fall in between the 4 required cases for initializer list and always requires all parameters to have default values, i.e. does not lead to the drawbacks to default arguments , which one should I choose and why? What is the best practice?
an example being
// option -1: for the default argument list
// my_array.h
my_array(int a_number_of_elements = 0, int default_val = 0);
//option-2 : default initalizer list
// my_array.h
my_array(int a_number_of_elements, int default_val);
//my_array.cpp
my_array:: my_array(int a_number_of_elements, int default_val)
: my_num_elements(a_num_elements), my_default_value(default_val)
Thanks for looking.
You are dealing with two completely different things here: constructor initializer lists vs default function arguments.
You got most of what you said correctly, but contrary to what you might believe, default constructor arguments do not imply the construction of data members using these values, unless you explicitly state so. Hence, one technique is not a replacement for the other, just separate complementary things.
For example:
// my_array.h
my_array(int a_number_of_elements = 1, int default_val = 0);
//my_array.cpp
my_array:: my_array(int a_number_of_elements, int default_val)
: my_num_elements(a_num_elements), my_default_value(default_val)
will [be expected to] initialize an array with one element of value zero.
If you do not explicitly call the constructors of the data members, then their default constructors, if available, will be called, so the following two are equivalent.
//implicitly default constructing members
my_array:: my_array()
{}
//explicitly default constructing members
my_array:: my_array() :
my_num_elements(), my_default_value()
{}
Regarding the two above, it is always a good idea to leave things explicit for better legibility. As often said, a given code is usually written once, but read many times.
You have a couple misconceptions here:
You are referring to "Constructor Initializer Lists" as initializer_lists
You seem to think that defaulted arguments can only be used separately from "Constructor Initialization Lists"
Lets talk about some principles here:
You'll always want to use a "Constructor Initializer List" for all your variables, not just those of the 4 types you mention. "Constructor Initializer Lists" value initialize, rather than default initializing and requiring you to assign to them in the constructor body
Where possible you'll always want to have a default constructor, as this is required for using your object in standard containers
Defaulting arguments is a great way to prevent code duplication for both a user defined constructor and a user defined default constructor
So using these principles I can say that the answer to your question is yes, that the ideal situation would be to to use both "Constructor Initializer Lists" and default arguments. Resulting in a constructor that looks something like:
my_array(int a_number_of_elements = 0, int default_val = 0) :
my_num_elements(a_number_of_elements),
my_default_value(default_val) {}

When should we not use initialization list in the constructor?

Can someone please quote an example code when we should not use initialisation list in the constructor and how that can be overcome with assignment?
I am looking for an example for the below statement
This might happen when your class has two constructors that need to initialize the this object's data members in different orders. Or it might happen when two data members are self-referential. Or when a data-member needs a reference to the this object, and you want to avoid a compiler warning about using the this keyword prior to the { that begins the constructor's body (when your particular compiler happens to issue that particular warning). Or when you need to do an if/throw test on a variable (parameter, global, etc.) prior to using that variable to initialize one of your this members.
I believe the main concept that the author of your statement was referring to is the fact that calls made to variables in the initialisation list occur not in the order you see them in the initialisation list, but in the order the variables are listed in the class definition.
That means
if you have two different constructors which use initialisation lists, they must initialise them in the same sequence
your control over sequencing (which may be important if you have mutually-dependent members) is limited
I'd recommend taking a look at Scott Meyer's Effective C++ which covers this (amongst many, many other useful and informative topics).
Here are some examples:
This might happen when your class has two constructors that need to
initialize the this object's data members in different orders.
class Example1 {
public:
Example1(std::string decoded, std::string encoded)
: decoded_(decoded),
encoded_(encoded) {}
explicit Example1(std::string encoded)
: decoded_(), // Can't use "decoded_(Decode())" since "encoded_" isn't initialised
encoded_(encoded) {
decoded_ = Decode(); // Assign here instead of initialising
}
private:
std::string Decode(); // decodes class member "encoded_"
std::string decoded_, encoded_;
};
In this example, decoded_ will always be initialised before encoded_ since that's the order in which they are declared in the class, even if we swap their order in the initialisation list.
Or when a data-member needs a reference to the this object, and you
want to avoid a compiler warning about using the this keyword prior to
the { that begins the constructor's body (when your particular
compiler happens to issue that particular warning).
class Example2 {
public:
Example2() : functor_() {
functor_ = std::bind(&Example2::Do, this);
}
private:
void Do();
std::function<void()> functor_;
};
Here, functor_ needs to use this when it is initialised/assigned. If we were to intialise functor_ in the initialisation list, the this pointer would be referring to an object which at that point wasn't fully initialised. That could be safe depending on the particular circumstances, but the foolproof option is to defer setting functor_ until inside the constructor body, by which point this does refer to a fully-initialised object.
Or when you need to do an if/throw test on a variable (parameter,
global, etc.) prior to using that variable to initialize one of your
this members.
class Example3 {
public:
Example3(int force, int acceleration)
: force_(force),
acceleration_(acceleration),
mass_(0) {
if (acceleration_ == 0)
throw std::exception("Can't divide by 0");
mass_ = force_ / acceleration_;
}
private:
int force_, acceleration_, mass_;
};
Hopefully this is self-explanatory.
I'm not sure what is meant by
when two data members are self-referential
so I can't give an example for that I'm afraid.