Search code examples
c++constructordynamic-memory-allocation

Proper way to writing constructors in C++


EDIT: Changed my question to something more meaningful

If i have a class:

class A{
public:
     int nr;
     int *a;

     A();
};

A::A(): nr(0), a = new int[10]{}

This chrases, but if I have

 A::A(): nr(0) {a = new int[10];}

It works. Please explain this behavior to me.


Solution

  • nr(0) is an initializer for the data member nr.

    {a = new T[10]; } is a constructor body that assigns a value to the data member a after the initialization in the initializer list has been performed.

    {} is an empty constructor body, it means the constructor does nothing (other than initialize nr, of course, since that's in the initializer list).

    a = new int[10] in between the initializer list and the constructor body is nonsense, the syntax of the language doesn't permit it. It shouldn't compile, but if you've found a compiler that accepts it and then it crashes, you'll have to look at that compiler's documentation for an explanation.