nakago
nakago

Reputation: 113

Initializing struct data members of a class

typedef struct _MY_STRUCT

{

         std::string     mystring;        
         int             n1;
         int             n2;
} MY_STRUCT;

class foo

{

public:

     foo():
         m_mystruct()
{ }

private:

     MY_STRUCT m_mystruct;
};

int main(void)

{

    foo oFoo;              
    // Why doesnt this intialize all data members of foo to NULL/0.
    // what is the correct way to get all members of MY_STRUCT to be intialized to NULL/0.   
}

Upvotes: 2

Views: 1482

Answers (3)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

First, you don't need to do typedef like this in C++. Second, create a default constructor for your structure:

struct MY_STRUCT
{
    std::string mystring;
    int n1;
    int n2;

    MY_STRUCT() : mystring(), n1(), n2() {}
};

This way the structure members will be default-initialized to:

  • std::string to empty string (via its default constructor),
  • ints to zero.

So the following holds:

MY_STRUCT ms;
assert( ms.mystring.empty());
assert( ms.n1 == 0 );
assert( ms.n2 == 0 );

Upvotes: 8

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145269

The reason is most probably that you're using Visual C++. Even as of version 10.0 Visual C++ does not do value initialization correctly. Your code works fine with g++ 4.4.1.

Around 2005 it was understandable that Visual C++ wasn't quite up to par, because the C++98 rules for initialization were changed in C++03. This was the only language change in C++03, which otherwise was just a "technical corrigendum" of C++98 (C++03 is sometimes called TC1, technical corrigendum 1). C++03 introduced "value initialization" as a generalization of "default initialization", in order to make the result less arbitrary and less baffling and just more practical for aggregate classes like yours, classes containing both POD and non-POD members: with C++03 rules those members are zero-initialized or default-initialized as appropriate, all of them. And it was a very good thing. T'was Andrew Koenig who proposed this, IIRC, and it weights up for his blame for Koenig Lookup (a.k.a. ADL, Argument Dependent Lookup). :-)

But as of 2010 it's a bit less understandable that Visual C++ doesn't do this correctly.

That said, your code is horrible. :-)

See the other comments for improvements to the code, including the idea of defining a constructor, which will fix the problem for Visual C++.

Cheers & hth.,

Upvotes: 0

C.J.
C.J.

Reputation: 16081

You could do just add a constructor to your struct definition:

typedef struct _MY_STRUCT

{
    _MY_STRUCT()
    {
        n1 = 0;
        n2 = 0;
    }
    std::string     mystring;        
    int             n1;
    int             n2;
} MY_STRUCT;

Upvotes: 2

Related Questions