Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. When to use class constructor member variable initializations?
Forum Updated to NodeBB v4.3 + New Features

When to use class constructor member variable initializations?

Scheduled Pinned Locked Moved Solved C++ Gurus
19 Posts 6 Posters 3.8k Views 5 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    JonB
    wrote on 23 Dec 2020, 09:52 last edited by
    #1

    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?

    1 Reply Last reply
    0
    • S Offline
      S Offline
      SGaist
      Lifetime Qt Champion
      wrote on 23 Dec 2020, 10:00 last edited by
      #2

      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.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      J 2 Replies Last reply 23 Dec 2020, 10:17
      5
      • C Online
        C Online
        Christian Ehrlicher
        Lifetime Qt Champion
        wrote on 23 Dec 2020, 10:02 last edited by
        #3

        @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

        Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
        Visit the Qt Academy at https://academy.qt.io/catalog

        J 1 Reply Last reply 23 Dec 2020, 10:24
        5
        • S SGaist
          23 Dec 2020, 10:00

          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.

          J Offline
          J Offline
          JonB
          wrote on 23 Dec 2020, 10:17 last edited by JonB
          #4

          @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++....

          1 Reply Last reply
          0
          • C Christian Ehrlicher
            23 Dec 2020, 10:02

            @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

            J Offline
            J Offline
            JonB
            wrote on 23 Dec 2020, 10:24 last edited by JonB
            #5

            @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....

            C 1 Reply Last reply 23 Dec 2020, 10:30
            0
            • S Offline
              S Offline
              SGaist
              Lifetime Qt Champion
              wrote on 23 Dec 2020, 10:30 last edited by
              #6

              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.

              Interested in AI ? www.idiap.ch
              Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

              1 Reply Last reply
              2
              • J JonB
                23 Dec 2020, 10:24

                @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....

                C Online
                C Online
                Christian Ehrlicher
                Lifetime Qt Champion
                wrote on 23 Dec 2020, 10:30 last edited by
                #7

                @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

                Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                Visit the Qt Academy at https://academy.qt.io/catalog

                J 1 Reply Last reply 23 Dec 2020, 10:36
                2
                • C Christian Ehrlicher
                  23 Dec 2020, 10:30

                  @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

                  J Offline
                  J Offline
                  JonB
                  wrote on 23 Dec 2020, 10:36 last edited by
                  #8

                  @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?

                  1 Reply Last reply
                  0
                  • C Online
                    C Online
                    Christian Ehrlicher
                    Lifetime Qt Champion
                    wrote on 23 Dec 2020, 10:40 last edited by
                    #9

                    @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.

                    Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                    Visit the Qt Academy at https://academy.qt.io/catalog

                    J 1 Reply Last reply 23 Dec 2020, 10:44
                    3
                    • S SGaist
                      23 Dec 2020, 10:00

                      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.

                      J Offline
                      J Offline
                      JonB
                      wrote on 23 Dec 2020, 10:42 last edited by
                      #10

                      @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?

                      1 Reply Last reply
                      0
                      • C Christian Ehrlicher
                        23 Dec 2020, 10:40

                        @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.

                        J Offline
                        J Offline
                        JonB
                        wrote on 23 Dec 2020, 10:44 last edited by JonB
                        #11

                        @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?

                        1 Reply Last reply
                        0
                        • C Online
                          C Online
                          Christian Ehrlicher
                          Lifetime Qt Champion
                          wrote on 23 Dec 2020, 10:46 last edited by
                          #12

                          @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)

                          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                          Visit the Qt Academy at https://academy.qt.io/catalog

                          J 1 Reply Last reply 23 Dec 2020, 10:49
                          2
                          • C Christian Ehrlicher
                            23 Dec 2020, 10:46

                            @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)

                            J Offline
                            J Offline
                            JonB
                            wrote on 23 Dec 2020, 10:49 last edited by
                            #13

                            @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?

                            1 Reply Last reply
                            0
                            • C Online
                              C Online
                              Christian Ehrlicher
                              Lifetime Qt Champion
                              wrote on 23 Dec 2020, 10:50 last edited by
                              #14

                              @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

                              Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                              Visit the Qt Academy at https://academy.qt.io/catalog

                              J 1 Reply Last reply 23 Dec 2020, 11:10
                              1
                              • C Christian Ehrlicher
                                23 Dec 2020, 10:50

                                @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

                                J Offline
                                J Offline
                                JonB
                                wrote on 23 Dec 2020, 11:10 last edited by JonB
                                #15

                                @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."].. :(

                                kshegunovK jeremy_kJ 2 Replies Last reply 23 Dec 2020, 11:28
                                0
                                • J JonB
                                  23 Dec 2020, 11:10

                                  @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."].. :(

                                  kshegunovK Offline
                                  kshegunovK Offline
                                  kshegunov
                                  Moderators
                                  wrote on 23 Dec 2020, 11:28 last edited by
                                  #16

                                  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?

                                  Read and abide by the Qt Code of Conduct

                                  1 Reply Last reply
                                  0
                                  • J JonB
                                    23 Dec 2020, 11:10

                                    @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."].. :(

                                    jeremy_kJ Offline
                                    jeremy_kJ Offline
                                    jeremy_k
                                    wrote on 31 Dec 2020, 08:40 last edited by
                                    #17

                                    @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.

                                    Asking a question about code? http://eel.is/iso-c++/testcase/

                                    J 1 Reply Last reply 31 Dec 2020, 08:49
                                    0
                                    • jeremy_kJ jeremy_k
                                      31 Dec 2020, 08:40

                                      @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.

                                      J Offline
                                      J Offline
                                      JonB
                                      wrote on 31 Dec 2020, 08:49 last edited by
                                      #18

                                      @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 ;-)

                                      1 Reply Last reply
                                      0
                                      • Kent-DorfmanK Offline
                                        Kent-DorfmanK Offline
                                        Kent-Dorfman
                                        wrote on 2 Jan 2021, 08:28 last edited by
                                        #19

                                        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.

                                        1 Reply Last reply
                                        0

                                        • Login

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • Users
                                        • Groups
                                        • Search
                                        • Get Qt Extensions
                                        • Unsolved