When to use class constructor member variable initializations?
-
In a post elsewhere on this site the user has gone for:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow), mTabWidget(new QTabWidget(this)), mSummaryPaymentWidget(new SummaryPaymentWidget(this)), mCategoryWidget(new CategoryWidget(this)), mStackedWidget(new QStackedWidget(this)) { ...
I use a variety of languages, C++ is only one of them. I don't think any of my other languages use this construct.
My question: does anyone think this is a actually a "nice/helpful style"? Seems to me, before you know it you could have 50 member variable initializations in the list, including trivia like
mCounter(0)
. I would just do these as the first statements in the body of the constructor. Where do you draw the line between the two approaches? -
Hi,
There's a comma issue there ;-)
I usually go with all member initialisation in that list.
That also allows you to get a nice warning if you put them out of order.
Note that with recent C++ standards, you can also do member initialisation at declaration time. See here for what is allowed.
-
@JonB said in When to use class constructor member variable initializations?:
I would just do these as the first statements in the body of the constructor.
This will initialize the parameters twice then, once in the initializer list, once in the ctor body. Even if you don't write it in the initializer list the compiler will create it.
Also note the new in-class member initialization method with c++11 -
@SGaist said in When to use class constructor member variable initializations?:
I usually go with all member initialisation in that list.
Well, you're the expert, all I can say is good luck. Why you would want to put potentially 50 member variable initializations as a comma list on the constructor is quite beyond me. Goodness knows what your list likes like when some of the initializers involve expressions which get a bit complicated, what it looks like when you put in blank lines and comments to explain what various bits are doing, how the editor handles folding/hiding, and so on. It must be pages-long.
So it looks I will be alone in saying I wouldn't do this in another language (because not supported), so I won't be doing it in C++....
-
@Christian-Ehrlicher said in When to use class constructor member variable initializations?:
Even if you don't write it in the initializer list the compiler will create it.
So if I write:
class Foo { int z; Foo() { }; }
this is treated as though I had written
int z{0}
/int z(0)
/int z = 0
? And there was I, thinking that. without an initializer of my own, class member variables (non-static) had no defined value.... -
If you have a member variables that has big and complex constructors that require a funky list of arguments, then you likely have a different issue.
For something that requires complex initialisation, I usually have a separate method that does that because it likely involves several steps that may fail and would like to have some status information about that. This allows to have an initial uninitialised state that you know is invalid for use. You can then initialise the object properly when required/needed with a better feedback than having to check if something failed during the construction.
-
@JonB said in When to use class constructor member variable initializations?:
And there was I, thinking that. without an initializer of my own, class member variables (non-static) had no defined value....
You're correct for PODs
-
@Christian-Ehrlicher said in When to use class constructor member variable initializations?:
You're correct for PODs
Argghh!! I am trying to learn! If you are retracting/qualifying your original, clear statement
Even if you don't write it in the initializer list the compiler will create it.
would you be kind enough to spell out exactly what you are saying for me?
-
@JonB said in When to use class constructor member variable initializations?:
would you be kind enough to spell out exactly what you are saying for me?
struct foo { std::string m_str; foo() } foo::foo() { m_str = "blub"; }
In this case in the ctor first std::string() is called by the compiler, then in the ctor body the string is assigned. When you do
foo::foo() : m_string("blub") {}
Then the std::string is assigned only once.
-
@SGaist said in When to use class constructor member variable initializations?:
Note that with recent C++ standards, you can also do member initialisation at declaration time. See here for what is allowed.
When I first (years ago, certainly before C++11) did some C++, I used to write:
class Foo { int z = 0; }
but the guy who was a C++-er said to me: don't do it there, do it explicitly in the constructor. Are you now saying we can/should do initialization in the class declaration after all? Or have I misunderstood?
-
@Christian-Ehrlicher said in When to use class constructor member variable initializations?:
Then the std::string is assigned only once.
Yes, I know that. But that does not apply if it's
int m_i
instead? So what things do or do not get this auto-initialization? I have to look at what feature about the type of every member variable to see where I am? -
@JonB said in When to use class constructor member variable initializations?:
don't do it there, do it explicitly in the constructor
This did not work before c++11
So what things do or do not get this auto-initialization?
They're undefined (
You're correct for PODs
) -
@Christian-Ehrlicher said in When to use class constructor member variable initializations?:
This did not work before c++11
What didn't work < C++ 11?
class Foo { int z = 0; }
didn't work??They're undefined (You're correct for PODs)
So are you saying I need to go look up whale pods for C++ in order to understand what is/is not initialized for class members?
-
@JonB said in When to use class constructor member variable initializations?:
I need to go look up whale pods for C++
See http://www.cplusplus.com/reference/type_traits/is_pod/
What didn't work < C++ 11? class Foo { int z = 0; } didn't work??
Correct
-
@Christian-Ehrlicher said in When to use class constructor member variable initializations?:
Correct
Indeed! Gosh, I did not know that, I thought it did work < C++11. Clearly my memory is not to be relied on.
I ended up reading https://www.boost.org/doc/libs/1_65_1/libs/utility/value_init.htm. Which goes through all this initializer stuff, and made my head hurt.
I realize that, not for the first time, I am in a minority of one not liking any of this stuff. I was getting to quite like C++ over the past months, despite my misgivings of the past. Now I'm remembering just why I found it arcane [e.g. "C++ has at least four different initialization notations, some of which overlap."].. :(
-
You know nothing Jon B. Actually, C++ was decently complicated to begin with, and is getting more complicated by the day. So the problem is trivial: when is the old stuff going to be cleaned up and the new stuff simplified? To which I suppose the answer's 'never'. How's that for a cheery perspective?
-
@JonB said in When to use class constructor member variable initializations?:
@Christian-Ehrlicher said in When to use class constructor member variable initializations?:
Correct
Indeed! Gosh, I did not know that, I thought it did work < C++11. Clearly my memory is not to be relied on.
It's possible that the compiler you used implemented this behavior as a non-standard extension. There were, and still are lots of cases of non-standard code having perfectly reasonable, compiler defined behavior.
-
@jeremy_k
In those days I --- or, to be accurate, much of the time my colleague, whose code I would have looked at --- would have been using Visual Studio/MSVC, say VS2010 plus its compiler. It's possible that might have allowed these initializations before the C++11 standard. Equally possible is that I just misremember ;-) -
I'd suggest that a class with many instance vars (traits) often indicates a design error and less than optimal use of subclassing. IOW, trying to do too much in a single scope. This is often the result of incremental development, without a clear architecture proposal before coding....not always, but often.
It's not critical to initialize vars by the initializer list, but do initialize them in proper order. I often defer trait initialization to a private Init() method because it looks cleaner. At least in recent c++ versions you can do nested constructors.