CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Join Date
    Nov 2010
    Posts
    105

    Question Why can't member variable be initialized?

    Why can't member variable be initialized (where it is declared)? What's the philosophy behind this rule? Thanks!

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Why can't member variable be initialized?

    If I understand your question correctly, you're asking why you can't do this:

    Code:
    struct A
    {
        int i = 0;
    };
    ?

    If that's the question, then the answer is: because it isn't clear when that assignment should take place written in that way. Any code outside of a function (global initializations etc) must be executed before main(), but here there is not yet any object to initialize. So when would the assignment take place? Presumably, upon construction of an A object, this would specify the initial values of its fields.

    That *would* be a perfectly reasonable interpretation....but that just isn't the way they chose to specify it. Instead, you have to do
    Code:
    struct A
    {
        int i;
        A(): i(0) {}
    };

  3. #3
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Why can't member variable be initialized?

    Quote Originally Posted by acppdummy View Post
    Why can't member variable be initialized (where it is declared)? What's the philosophy behind this rule? Thanks!
    What you are referring to though would be providing default values to member variables at the point of declaration, rather than in each and every constructor.

    At the time of creating C (and their structs), there was no such thing as construction. In C++, they probably didn't even think about it. They considered it for C++0x, but finally dropped it.

    To be perfectly honest, I think it would be one of those features that provides some nice sugar, but nobody actually really needs, but that would potentially be a snake's pit of extra bugs, obscurely dangerous rules, and bad patterns.

    Take for example initializing static const integers at declaration in a class. Some compilers STILL don't support it more than 10 years after standardization, and a lot of developers have to resort to the enum hack. Imagine the chaos this pitiful feature would create. I think that is the philosophy for not importing it.

    Any ways, my 2c. I think it's just not the way they did things, and nobody is losing much sleep over it.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  4. #4
    Join Date
    Nov 2010
    Posts
    105

    Re: Why can't member variable be initialized?

    Quote Originally Posted by Lindley View Post
    .... Instead, you have to do
    Code:
    struct A
    {
        int i;
        A(): i(0) {}
    };
    Thank you! I suppose this is equivalent to setting the values in the body of the constructor function? Like
    A(){i=0;}
    ?
    Last edited by acppdummy; November 16th, 2010 at 11:13 AM.

  5. #5
    Join Date
    Nov 2010
    Posts
    105

    Re: Why can't member variable be initialized?

    Quote Originally Posted by monarch_dodra View Post
    What you are referring to though would be providing default values to member variables at the point of declaration, rather than in each and every constructor.

    At the time of creating C (and their structs), there was no such thing as construction. In C++, they probably didn't even think about it. They considered it for C++0x, but finally dropped it.

    To be perfectly honest, I think it would be one of those features that provides some nice sugar, but nobody actually really needs, but that would potentially be a snake's pit of extra bugs, obscurely dangerous rules, and bad patterns.

    Take for example initializing static const integers at declaration in a class. Some compilers STILL don't support it more than 10 years after standardization, and a lot of developers have to resort to the enum hack. Imagine the chaos this pitiful feature would create. I think that is the philosophy for not importing it.

    Any ways, my 2c. I think it's just not the way they did things, and nobody is losing much sleep over it.
    Thanks!

  6. #6
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Why can't member variable be initialized?

    Quote Originally Posted by acppdummy
    I suppose this is equivalent to setting the values in the body of the constructor function?
    Not quite: this is initialisation, but assigning in the body of the constructor is assignment. This is an important difference when the member variable is const or of a reference type, and also if the member variable is of a class type whose default constructor does something significant (or which does not have a default constructor). In Lindley's example, it is merely of a built-in type, so there is pretty much no net difference.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  7. #7
    Join Date
    Nov 2010
    Posts
    105

    Re: Why can't member variable be initialized?

    Quote Originally Posted by laserlight View Post
    Not quite: this is initialisation, but assigning in the body of the constructor is assignment. This is an important difference when the member variable is const or of a reference type, and also if the member variable is of a class type whose default constructor does something significant (or which does not have a default constructor). In Lindley's example, it is merely of a built-in type, so there is pretty much no net difference.
    Thank you! There is sill a lot for me to learn. So bottom line if the member variable is just simple int or double type then either way is fine, right?

  8. #8
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Why can't member variable be initialized?

    Quote Originally Posted by acppdummy
    So bottom line if the member variable is just simple int or double type then either way is fine, right?
    Yes, but you might as well use the initialiser list anyway. After all, if you intend to initialise, then initialise, not assign.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  9. #9
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Why can't member variable be initialized?

    Quote Originally Posted by acppdummy View Post
    Thank you! There is sill a lot for me to learn. So bottom line if the member variable is just simple int or double type then either way is fine, right?
    Coding standards often say to put every member in the initializer list (not sure that is the correct term), even if just to default initialize it:

    Code:
    class myClass
    {
    public:
        myClass() : myString(), //default construction
                   myInt(5)  //initialize to 5
        {}
    
    private:
        std::string myString;
        int myInt;
    }
    Something you should take into account is that members are ALWAYS constructed in the same order they are declared in the class body. As such ALWAYS put them in the SAME order in your constructor. While it is legal, to put them in a different order, it is very immoral to do so.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  10. #10
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Why can't member variable be initialized?

    No.

    The only members that can be initialised inside the struct/class definition are static const integral members.

    What you don't seem to be getting is a struct/class definition is not an object but a map for making objects, a blueprint if you like.

    Objects may all be made from the same blueprint but their members may vary widely depending on the arguments passed to the constructor called to make the object. This is why its the constructors job to initialise the variables and why you cant do it as you would seem to like.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  11. #11
    Join Date
    Nov 2010
    Posts
    105

    Re: Why can't member variable be initialized?

    Thanks to all again!

  12. #12
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150

    Re: Why can't member variable be initialized?

    Quote Originally Posted by monarch_dodra
    At the time of creating C (and their structs), there was no such thing as construction. In C++, they probably didn't even think about it. They considered it for C++0x, but finally dropped it.
    What was dropped in C++0x? Any references?
    The following code is perfectly valid in C++0x (draft version ISO/IEC JTC1 SC22 WG21 N3092)
    Code:
    struct A
    {
        int i = 0;
    };
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  13. #13
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Why can't member variable be initialized?

    Quote Originally Posted by monarch_dodra View Post
    As such ALWAYS put them in the SAME order in your constructor. While it is legal, to put them in a different order, it is very immoral to do so.
    It's also exceedingly difficult to catch a problem if one initialization requires another one already be initialized.

    Code:
    struct autoCString{
       autoCString(char * temp) : myptr(temp), len(strlen(myptr)){}
       ~autoCString(void){free(myptr);}
       int len;
       char * myptr;
    };
    No compiler errors, or even warnings (on most compilers) but will crash every time.

    What was the reasoning for this anyway?

  14. #14
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Why can't member variable be initialized?

    Quote Originally Posted by Marc G View Post
    What was dropped in C++0x? Any references?
    The following code is perfectly valid in C++0x (draft version ISO/IEC JTC1 SC22 WG21 N3092)
    Code:
    struct A
    {
        int i = 0;
    };
    Last time I investigated was on september 22nd, one day after the release of draft n3126, when this change appeared on wikipedia's C++0x article.

    I tried to find the change in n3126, but couldn't find anything (I mainly searched 9 Classes, 12.6 Initialization and 12.7 Construction). I realize there is no reference associated with the remove, but at the same time, the removed content didn't have references either. I just left it at that.

    If anybody could find the correct reference that proves this feature is still (or isn't) in the standard as of draft n3126, I would be thrilled.

    If nothing comes up, I'll try to contact User:Kwamikagami to ask him about it.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  15. #15
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Why can't member variable be initialized?

    Quote Originally Posted by monarch_dodra
    If anybody could find the correct reference that proves this feature is still (or isn't) in the standard as of draft n3126, I would be thrilled.
    That was easy
    Refer to the example in n3126 clause 12.6.2 paragraph 8.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Page 1 of 2 12 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured