0

I totally disappointed. I have class, there I have private structure. And what's the silly problem: I just can't preinitialize some variables!
What I mean:
I need:

struct someStruct
    {
        someStruct *next = NULL;
        int number;
    };

I just want to create easy dynamic list, adding new elements from heap.
And what I should do?

struct someStruct
    {
        someStruct *next;
        int number;
    };

Put

someStruct *newElement = new someStruct;
newElement.next = NULL;

every time? I can forget about this.
Please help me. Because it's not a problem when I need to add 1 useless string. But what if I have 50 default variables?

trincot
  • 317,000
  • 35
  • 244
  • 286
Destiner
  • 540
  • 4
  • 16
  • 1
    http://stackoverflow.com/questions/3102096/when-do-c-pod-types-get-zero-initialized – Mat Aug 10 '13 at 14:16

1 Answers1

2

You cannot initialize class members when you declare them. Instead, you need a constructor:

struct someStruct {
    someStruct(): next(NULL), number(0) {}
    someStruct *next;
    int number;
};

Alternatively, for POD (plain old data), you could use your original class with no constructors and use someStruct *newElement = new someStruct(); to create a someStruct. This initializes the members to zero.

Also, C++11 supports in-class member initializers.

Community
  • 1
  • 1
Yang
  • 7,712
  • 9
  • 48
  • 65
  • 2
    Alternatively, initialize a the point of declaration in C++11. – juanchopanza Aug 10 '13 at 14:18
  • Alternative 2: `someStruct *newElement = new someStrsomeStruct();`, requires no modification to the original class. – juanchopanza Aug 10 '13 at 14:25
  • @Destiner You can find a list of supported C++11 features at http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx. Currently, Non-static data member initializers aren't supported. – Yang Aug 10 '13 at 15:01