class initialization list - c++

Just a simple question about c++ coding style,
for example, all member variables of a class will be called with the default constructor in the initialization list if we don't do anything else. B default constructor will be called and value will be set to 0, int();
class A
{
A();
private:
B b;
int value;
}
However my question is, even do the default constructor will be called is it a good habit to always do it yourself or does it only add extra lines to the code
A::A() : b(), value() {}

You are touching on one of the sticky corners of C++.
The initialization of POD values in objects is sticky and depends on a few things.
Even I am not sure I can get all the rules correct but I believe #Steve Jessop once wrote an article about here on SO (though I can currently find it).
But some examples:
This class will always be initialized b == false and value = 0.
class A
{
A() : b(), value() {}
B b;
int value;
};
Without an explicit default constructor it is more complex:
Here the compiler will generate a default constructor for you. But how the compiler generated default constructor works depends on the situation. The compiler generated default constructor can do two different forms of initialization and which is used depends on context:
Zero Initialization (All POD members are zero'ed out)
Value Initialization (All POD members are left undefined)
Example:
class B
{
B b;
int value;
};
// Variables of static storage duration (notably globals)
// Will be zero initialized and thus b == false and value = 0
B global; // Initialized
int main()
{
// Object of automatic storage duration or dynamic storage duration
// These will depend on how they are declared.
// Value Initialization (POD re-mains undefined)
B bo1; // b/value undefined
B* bp1 = new B; // b.balue undefined
// Zero Initialization
B bo2 = B(); // b = false, value = 0
B* bp2 = new B(); // b = false, value = 0
// Note: The most obvious syntax for zero initializing a local object
// does not work as it is actually interpreted as a forward
// declaration of a function;
B bo3();
}

It's a good idea to leave the default constructor out. The compiler-generated constructors are much more reliable and maintainable than writing your own versions, and apart from anything else, it's a flat out waste of time to write code the compiler could write for you. If you don't need any construction logic, then don't write a constructor.
However, the int will not be initialized unless you do it, which is a sucky reason to have to write a constructor.

By default int variables are not initialized with a value - you have to do it yourself.
So when you don't set the member variable "value" to some value in the constructor it is left uninitialized.

The default constructor will only be called for class types with default constructors, not for primitives.

Related

Is default constructor is better than user defined in C++11 if it's exactly the same?

How is the compiler-generated constructor more efficient than the one we provide, if we provide exactly the same constructor?
i.e., does the compiler add any extra code to its default constructor, such that providing our own user-defined constructor is less efficient?
Simply put, how is default constructor generated in:
struct widget
{
// default ctor generated
};
More efficient than the one provided in this:
struct widget
{
widget(){} // user-defined but exactly the same
};
If you write widget() = default; (in the class body only), the resulting constructor is exactly the same as the generated one.
Those two have an obscure property that widget() {} doesn't have: value-initializing such a class would value-initialize all fields that would otherwise be uninitialized.
Example:
struct A
{
int x;
int y = 1;
// This changes nothing:
// A() = default;
};
struct B
{
int x;
int y = 1;
B() {}
};
A a1; // `x` is uninitialized `y` is 1
A a2{}; // `x` is 0 `y` is 1
B b1; // `x` is uninitialized `y` is 1
B b2{}; // `x` is uninitialized `y` is 1
Only use widget() = default; or the generated constructor if you want to take advantage of having two distinct initialization strategies, or if you don't have uninitialized members.
Otherwise use widget() {} to make sure you don't accidentally perform useless initialization.
Libstdc++ has fallen into this trap with their std::optional implementation, see std::optional - construct empty with {} or std::nullopt?
How is the compiler-generated constructor more efficient than the one we provide, if we provide exactly the same constructor?
It isn't, they generate the same code in reasonable compilers.
But there is nothing that forces a compiler to generate the exact same code. As long as the observable behavior is the same..
i.e., does the compiler add any extra code to its default constructor, such that providing our own user-defined constructor is less efficient?
No, in reasonable compilers.

Are members of a class with defaulted constructors zero-initialized? [duplicate]

Does the default constructor (created by the compiler) initialize built-in-types?
Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.
However, you have to keep in mind that in some cases the initialization of a instance of the class can be performed by other means. Not by default constructor, nor by constructor at all.
For example, there's a widespread incorrect belief that for class C the syntax C() always invokes default constructor. In reality though, the syntax C() performs so called value-initialization of the class instance. It will only invoke the default constructor if it is user-declared. (That's in C++03. In C++98 - only if the class is non-POD). If the class has no user-declared constructor, then the C() will not call the compiler-provided default constructor, but rather will perform a special kind of initialization that does not involve the constructor of C at all. Instead, it will directly value-initialize every member of the class. For built-in types it results in zero-initialization.
For example, if your class has no user-declared constructor
class C {
public:
int x;
};
then the compiler will implicitly provide one. The compiler-provided constructor will do nothing, meaning that it will not initialize C::x
C c; // Compiler-provided default constructor is used
// Here `c.x` contains garbage
Nevertheless, the following initializations will zero-initialize x because they use the explicit () initializer
C c = C(); // Does not use default constructor for `C()` part
// Uses value-initialization feature instead
assert(c.x == 0);
C *pc = new C(); // Does not use default constructor for `C()` part
// Uses value-initialization feature instead
assert(pc->x == 0);
The behavior of () initializer is different in some respects between C++98 and C++03, but not in this case. For the above class C it will be the same: () initializer performs zero initialization of C::x.
Another example of initialization that is performed without involving constructor is, of course, aggregate initialization
C c = {}; // Does not use any `C` constructors at all. Same as C c{}; in C++11.
assert(c.x == 0);
C d{}; // C++11 style aggregate initialization.
assert(d.x == 0);
I'm not quite certain what you mean, but:
struct A { int x; };
int a; // a is initialized to 0
A b; // b.x is initialized to 0
int main() {
int c; // c is not initialized
int d = int(); // d is initialized to 0
A e; // e.x is not initialized
A f = A(); // f.x is initialized to 0
}
In each case where I say "not initialized" - you might find that your compiler gives it a consistent value, but the standard doesn't require it.
A lot of hand-waving gets thrown around, including by me, about how built-in types "in effect" have a default constructor. Actually default initialization and value initialization are defined terms in the standard, which personally I have to look up every time. Only classes are defined in the standard to have an implicit default constructor.
For all practical purposes - no.
However for implementations that are technically compliant with the C++ standard, the answer is that it depends whether the object is POD or not and on how you initialize it.
According to the C++ standard:
MyNonPodClass instance1;//built in members will not be initialized
MyPodClass instance2;//built in members will be not be initialized
MyPodClass* instance3 = new MyPodClass;//built in members will not be initialized
MyPodClass* instance3 = new MyPodClass() ;//built in members will be zero initialized
However, in the real world, this isn't well supported so don't use it.
The relevant parts of the standard are section 8.5.5 and 8.5.7
As per the standard, it doesn't unless you explicitly initialize in initializer list
As previous speakers have stated - no, they are not initialized.
This is actually a source for really strange errors as modern OSs tend to fill newly allocated memory regions with zeroes. If you expect that, it might work the first time. However, as your application keeps running, delete-ing and new-ing objects, you will sooner or later end up in a situation where you expect zeroes but a non-zero leftover from an earlier object sits.
So, why is this then, isn't all new-ed data newly allocated? Yes, but not always from the OS. The OS tends to work with larger chunks of memory (e.g. 4MB at a time) so all the tiny one-word-here-three-bytes-there-allocations and deallocations are handled in uyserspace, and thus not zeroed out.
PS. I wrote "tend to", i.e. you can't even rely on success the first time...
Technically it does initialize them -- by using their default constructor, which incidentally does nothing but allocate the memory for them.
If what you wanted to know is whether or not they are set to something sane like 0 for ints, then the answer is "no".
No. The default constructor allocates memory and calls the no-argument constructor of any parents.

Can I depend upon a new bool being initialized to false?

In C++, can I depend upon a new bool being initialized to false in all cases?
bool *myBool = new bool();
assert(false == *myBool); // Always the case in a proper C++ implementation?
(Updated code to reflect comment.)
In this case, yes; but the reason is quite subtle.
The parentheses in new bool() cause value-initialisation, which initialises it as false. Without them, new bool will instead do default-initialisation, which leaves it with an unspecified value.
Personally, I'd rather see new bool(false) if possible, to make it clear that it should be initialised.
(That's assuming that there is a good reason for using new at all; and even if there is, it should be managed by a smart pointer - but that's beyond the scope of this question).
NOTE: this answers the question as it was when I read it; it had been edited to change its meaning after the other answer was written.
The three relevant kinds of initialization, zero-initialization, default-initialization, and value-initialization for bool mean, respectively, that the bool is initialized to false, that the bool has an indeterminate value, and that the bool is initialized to false.
So you simply need to ensure that you're getting zero or value initialization. If an object with automatic or dynamic storage duration is initialized without an initializer specified then you get default-initialization. To get value-initialization you need an empty initializer, either () or {}.
bool b{}; // b is value-initialized
bool *b2 = new bool{}; // *b2 is value-initialized
class foo {
bool b;
foo() : b() {}
};
foo f; // // f.b is value-initialized
You get zero initialization for a bool that has static or thread local storage duration and does not have an initializer.
static bool b; // b is zero-initialized
thread_local bool b2; // b2 is zero-initialized
One other case where you get zero-initialization is if the bool is a member of a class without a user-provided constructor and the implicit default constructor is trivial, and the class instance is zero- or value-initialized.
class foo {
bool b;
};
foo f{}; // f.b is zero-initialized
thread_local foo f2; // f2.b is zero-initialized
No. There is no automatic initialization in C++. Your new bool will be "initialized" to whatever was in memory at that moment, which is more likely to be true (since any non-zero value is true), but there is no guarantee either way.
You might get lucky and use a compiler that plays nice with you and will always assign a false value to a new bool, but that would be compiler dependent and not based on any language standard.
You should always initialize your variables.

Does a c++ struct have a default constructor?

I wrote the following code snippet:
void foo()
{
struct _bar_
{
int a;
} bar;
cout << "Value of a is " << bar.a;
}
and compiled it with g++ 4.2.1 (Mac). The output is "Value of a is 0".
Is it true to say that data members of a struct in c++ are always initialized by default (compared to c)? Or is the observed result just coincidence?
I can imagine that structs in c++ have a default constructor (since a struct and a class is almost the same in c++), which would explain why the data member a of bar is initialized to zero.
The simple answer is yes.
It has a default constructor.
Note: struct and class are identical (apart from the default state of the accesses specifiers).
But whether it initializes the members will depends on how the actual object is declared. In your example no the member is not initialized and a has indeterminate value.
void func()
{
_bar_ a; // Members are NOT initialized.
_bar_ b = _bar_(); // Members are zero-initialized
// From C++14
_bar_ c{}; // New Brace initializer (Members are zero-initialized)
_bar_* aP = new _bar_; // Members are NOT initialized.
_bar_* bP = new _bar_(); // Members are zero-initialized
// From C++14
_bar_ cP = new _bar_{}; // New Brace initializer (Members are zero-initialized)
}
// static storage duration objects
// i.e. objects at the global scope.
_bar_ c; // Members are zero-initialized.
The exact details are explained in the standard at 8.5 Initializers [dcl.init] paragraphs 4-10. But the following is a simplistic summary for this situation.
A structure without a user defined constructor has a compiler generated constructor. But what it does depends on how it is used and it will either default initialize its members (which for POD types is usually nothing) or it may zero initialize its members (which for POD usually means set its members to zero).
PS. Don't use a _ as the first character in a type name. You will bump into problems.
Is it true to say that data members of a struct in c++ are always initialized by default (compared to c)? Or is the observed result just coincidence?
It is a coincidence.
Your code invokes Undefined Behavior; unless you explicitly set the members to 0 they can be anything.
Not an answer, but you might take it to be... if you want to try it:
void foo() {
struct test {
int value;
} x;
std::cout << x.value << std::endl;
x.value = 1000;
}
int main() {
foo();
foo();
}
In your example, the memory already had the 0 value before the variable was created, so you can call it a lucky coincidence (in fact, some OS will zero out all memory before starting a process, which means that 0 is quite a likely value to find in a small short program...), the previous code will call the function twice, and the memory from the first call will be reused in the second one, chances are that the second time around it will print 1000. Note however that the value is still undefined, and that this test might or not show the expected result (i.e. there are many things that the compiler can do and would generate a different result...)
Member variables of a struct are not initialized by default. Just like a class (because a struct is exactly the same thing as a class, only in struct the members are public by default).
Do not rely on this functionality it is non-standard
just add
foo() : a() {}
I can't remember the exact state of gcc 4.2 (i think it is too old) but if you were using C++11 you can do the following
foo()=default;

Initialisation and assignment

What EXACTLY is the difference between INITIALIZATION and ASSIGNMENT ?
PS : If possible please give examples in C and C++ , specifically .
Actually , I was confused by these statements ...
C++ provides another way of initializing member variables that allows us to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.
Using an initialization list is very similar to doing implicit assignments.
Oh my. Initialization and assignment. Well, that's confusion for sure!
To initialize is to make ready for use. And when we're talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment.
So it's pretty subtle: assignment is one way to do initialization.
Assignment works well for initializing e.g. an int, but it doesn't work well for initializing e.g. a std::string. Why? Because the std::string object contains at least one pointer to dynamically allocated memory, and
if the object has not yet been initialized, that pointer needs to be set to point at a properly allocated buffer (block of memory to hold the string contents), but
if the object has already been initialized, then an assignment may have to deallocate the old buffer and allocate a new one.
So the std::string object's assignment operator evidently has to behave in two different ways, depending on whether the object has already been initialized or not!
Of course it doesn't behave in two different ways. Instead, for a std::string object the initialization is taken care of by a constructor. You can say that a constructor's job is to take the area of memory that will represent the object, and change the arbitrary bits there to something suitable for the object type, something that represents a valid object state.
That initialization from raw memory should ideally be done once for each object, before any other operations on the object.
And the C++ rules effectively guarantee that. At least as long as you don't use very low level facilities. One might call that the C++ construction guarantee.
So, this means that when you do
std::string s( "one" );
then you're doing simple construction from raw memory, but when you do
std::string s;
s = "two";
then you're first constructing s (with an object state representing an empty string), and then assigning to this already initialized s.
And that, finally, allows me to answer your question. From the point of view of language independent programming the first useful value is presumably the one that's assigned, and so in this view one thinks of the assignment as initialization. Yet, at the C++ technical level initialization has already been done, by a call of std::string's default constructor, so at this level one thinks of the declaration as initialization, and the assignment as just a later change of value.
So, especially the term "initialization" depends on the context!
Simply apply some common sense to sort out what Someone Else probably means.
Cheers & hth.,
In the simplest of terms:
int a = 0; // initialization of a to 0
a = 1; // assignment of a to 1
For built in types its relatively straight forward. For user defined types it can get more complex. Have a look at this article.
For instance:
class A
{
public:
A() : val_(0) // initializer list, initializes val_
{}
A(const int v) : val_(v) // initializes val_
{}
A(const A& rhs) : val_(rhs.val_) // still initialization of val_
{}
private:
int val_;
};
// all initialization:
A a;
A a2(4);
A a3(a2);
a = a3; // assignment
Initialization is creating an instance(of type) with certain value.
int i = 0;
Assignment is to give value to an already created instance(of type).
int i;
i = 0
To Answer your edited Question:
What is the difference between Initializing And Assignment inside constructor? &
What is the advantage?
There is a difference between Initializing a member using initializer list and assigning it an value inside the constructor body.
When you initialize fields via initializer list the constructors will be called once.
If you use the assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.
As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.
For an integer data type or POD class members there is no practical overhead.
An Code Example:
class Myclass
{
public:
Myclass (unsigned int param) : param_ (param)
{
}
unsigned int param () const
{
return param_;
}
private:
unsigned int param_;
};
In the above example:
Myclass (unsigned int param) : param_ (param)
This construct is called a Member Initializer List in C++.
It initializes a member param_ to a value param.
When do you HAVE TO use member Initializer list?
You will have(rather forced) to use a Member Initializer list if:
Your class has a reference member
Your class has a const member or
Your class doesn't have a default constructor
Initialisation: giving an object an initial value:
int a(0);
int b = 2;
int c = a;
int d(c);
std::vector<int> e;
Assignment: assigning a new value to an object:
a = b;
b = 5;
c = a;
d = 2;
In C the general syntax for initialization is with {}:
struct toto { unsigned a; double c[2] };
struct toto T = { 3, { 4.5, 3.1 } };
struct toto S = { .c = { [1] = 7.0 }, .a = 32 };
The one for S is called "designated initializers" and is only available from C99 onward.
Fields that are omitted are automatically initialized with the
correct 0 for the corresponding type.
this syntax applies even to basic data types like double r = { 1.0
};
There is a catchall initializer that sets all fields to 0, namely { 0 }.
if the variable is of static linkage all expressions of the
initializer must be constant expressions
This {} syntax can not be used directly for assignment, but in C99 you can use compound literals instead like
S = (struct toto){ .c = { [1] = 5.0 } };
So by first creating a temporary object on the RHS and assigning this to your object.
One thing that nobody has yet mentioned is the difference between initialisation and assignment of class fields in the constructor.
Let us consider the class:
class Thing
{
int num;
char c;
public:
Thing();
};
Thing::Thing()
: num(5)
{
c = 'a';
}
What we have here is a constructor that initialises Thing::num to the value of 5, and assigns 'a' to Thing::c. In this case the difference is minor, but as was said before if you were to substitute int and char in this example for some arbitrary classes, we would be talking about the difference between calling a parameterised constructor versus a default constructor followed by operator= function.