Reputation: 219
I'm trying to understand fully how a constructor works in C++. Specifically, the member initialization list of a constructor.
Say you have a class Foobar with three data members bar, baz, and qux.
I set up my constructor like this:
Foobar(int bar, int baz, int qux)
: bar(bar), baz(baz), qux(qux)
{
// empty constructor body
}
My question is, does the member initialization list act as a "default"? Or does it ALWAYS happen? If, for example, the constructor was called with arguments, would the initialization list be ignored? I want to always have the qux data member be 0, unless otherwise specified. So would I instead write the member initialization line as:
: nar(bar), bar(baz), qux(0)
Perhaps I'm totally misunderstanding the function of the member initialization list and maybe someone can set me straight.
Upvotes: 1
Views: 163
Reputation: 437346
That constructor cannot be called without arguments, as all three of them are required. The compiler will remind you if you forget.
If you always want to initialize a member to a fixed value, the way to do that is exactly what you propose.
Upvotes: 1