0

Suppose I have a struct with a type that possesses a constructor:

struct my_struct {
   array2D<double> arr;
   array2D<double> arr2; etc.
}

// where I would typically generate arr like: 
int n = 50; int m = 100;
array2D<double> arr(n,m);

Right now, I initialize my struct as follows:

struct my_struct {
    array2D<double> arr;
    my_struct(n,m){
        array2D<double> this_arr(n,m);
        this->arr = this_arr;
    }
}

Is there a way to access the constructor like so (in pseudo code):

struct my_struct{
    array2D<double> arr;
    my_struct(n,m){
         this->arr(n,m);
    }
}

Right now, I am holding pointers in my struct...but then using the struct is beside the point, because I am trying to use the struct to clean up the code.

Chris
  • 28,822
  • 27
  • 83
  • 158
  • 2
    The usefulness of the Member Initializer List vs the frequency that it is taught is right up there with the debugger. – user4581301 Nov 30 '17 at 16:50
  • Possible duplicate of [C++ Member Initialization List](https://stackoverflow.com/questions/7665021/c-member-initialization-list) – 1201ProgramAlarm Nov 30 '17 at 17:21

3 Answers3

1

Use a member initializer list:

struct my_struct{
    array2D<double> arr;
    my_struct(n,m)
         : arr(n,m)
    {
    }
}
0x5453
  • 12,753
  • 1
  • 32
  • 61
1

What you're looking for is the initializer list:

struct my_struct{
    array2D<double> arr;
    my_struct(n,m) : arr(n, m) { }
}
mnistic
  • 10,866
  • 2
  • 19
  • 33
1

You need to make use of the constructor's initializer list. Before the constructor's body, you may list any of that class' members or base class for initialization.

struct my_struct 
{
    array2D<double> arr;
    my_struct(int n, int m) : arr(n, m)
    { }
};

Members and base classes that do not appear in the initializer list (or all of them if the list is not present) will first be default constructed. Even if you try to assign a value to those members in the body of the constructor, they will still first be initialized with no arguments. Note that base classes are initialized first, then the members in the order they appear in the class declaration regardless of the order they appear in the initializer list.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • nvm--great answer; thanks for the simple example and the explanation. otherwise, all the answers are great. – Chris Nov 30 '17 at 16:56