Recently I've seen an example like the following:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
What does this strange : bar(num)
mean? It somehow seems to initialize the member variable but I've never seen this syntax before. It looks like a function/constructor call but for an int
? Makes no sense for me. Perhaps someone could enlighten me. And, by the way, are there any other esoteric language features like this, you'll never find in a ordinary C++ book?
This is an initialization list. It'll initialize the members before the constructor body is run. Consider
vs
In the first example, str will be initialized by its no-argument constructor
before the body of the Foo constructor. Inside the foo constructor, the
will be called on 'str' as you do str = p;
Wheras in the second example, str will be initialized directly by calling its constructor
with 'p' as an argument.
It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
there is another 'benefit'
if the member variable type does not support null initialization or if its a reference (which cannot be null initialized) then you have no choice but to supply an initialization list
That's constructor initialisation. It is the correct way to initialise members in a class constructor, as it prevents the default constructor being invoked.
Consider these two examples:
In example 1:
In example 2:
It's all about efficiency.
You are correct, this is indeed a way to initialize member variables. I'm not sure that there's much benefit to this, other than clearly expressing that it's an initialization. Having a "bar=num" inside the code could get moved around, deleted, or misinterpreted much more easily.
Not mentioned yet on this thread: since C++11, the member initializer list can use list-initialization (aka. "uniform initialization", "braced initialization"):
which has the same semantics as list-initialization in other contexts.