1

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.

Sabien
  • 219
  • 2
  • 16
  • 1
    I think your confusion is caused by the fact that your constructor's parameter names are the same as the member names. While this is legal, I would recommend you use different names, perhaps by simply prefixing your parameters with an underscore. – Benjamin Lindley Aug 30 '14 at 23:53
  • possible duplicate of [What is this weird colon-member syntax in the constructor?](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) – Timbo Aug 30 '14 at 23:53
  • @BenjaminLindley Why use a silly underscore for a language rule that everybody knows about? #IdRatherNotUnderscore – Captain Giraffe Aug 31 '14 at 00:05
  • @CaptainGiraffe: Because not everybody knows about it. And underscores aren't silly, they're fantastic. – Benjamin Lindley Aug 31 '14 at 00:07
  • @BenjaminLindley They have an implied meaning. That is nowhere near fantastic. – Captain Giraffe Aug 31 '14 at 00:09
  • If they are strings instead of ints, does that change anything? In my book they did this exactly, but they were strings...My understanding was that they were initialized to empty strings. – Sabien Aug 31 '14 at 00:16
  • If you want default values I would suggest using [in class member intializers](http://stackoverflow.com/q/24149924/1708801). – Shafik Yaghmour Aug 31 '14 at 00:50

1 Answers1

1

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.

Jon
  • 428,835
  • 81
  • 738
  • 806