Aaron Campbell
Aaron Campbell

Reputation: 602

C++ Initialize object member of a struct that is allocated using the "new" keyword

This may be a complicated question but I assume it has a simple answer.

So I have a struct that contains custom object types:

// header1.h

struct MyStruct
{
    MyClass myObject1;
    MyClass myObject2;
};

And I have a global pointer to a MyStruct. I am going to allocate and instantiate the struct using the new keyword. When I do so, I want to construct each myObject by name in an initializer list, as shown below.

// codeFile1.cpp

MyStruct *myStructPtr;

int main()
{
    myStructPtr = new MyStruct
    {                                     //syntax error: missing ';'
        .myObject1 = MyClass(arg1, arg2),
        .myObject2 = MyClass(arg1, arg2)
    };
}

The code snippet above has syntax errors, but it demonstrates what I want to do. Note that MyClass does not have a default constructor, so it must be given an argument list.

Thanks!

EDIT - CONCLUSION

As pointed out, my initialization list is C-style, which fails to work. Unfortunately the C++11 initializer-list does not meet my compiler requirements, and the option of throwing all arguments into a constructor is not practical.

So I took an alternative solution and changed the pointer structure to the following:

// header1.h

struct MyStruct
{
    MyClass *myObjectPtr1;
    MyClass *myObjectPtr2;
};

// codeFile1.cpp

MyStruct myStruct;

int main()
{
    myStructPtr.myObjectPtr1 = new MyClass(arg1, arg2);
    myStructPtr.myObjectPtr2 = new MyClass(arg1, arg2);
}

Thanks all!

Upvotes: 3

Views: 4218

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129344

You will, somehow, need to chain your constructions together. Assuming you actually want the same arguments:

struct MyStruct
{
    MyStruct(int arg1, int arg2) : myObject(arg1, arg2), myObejct2(arg1, arg2) {}
    MyClass myObject1;
    MyClass myObject2;
};

MyStruct *s = new MyStruct(34, 42);

Or something like this:

struct MyStruct
{
    MyStruct(const MyClass& a1, const MyClass& a2) : myObject(a1), myObejct2(a2) {}
 .... 
};

MyStruct *s = new MyStruct(MyClass(1,2), MyClass(3,4));

or in C++11 initializer lists:

MyStruct *s = new MyStruct({1,2}, {3,4});

Many other similar solutions are available.

Upvotes: 1

Pradhan
Pradhan

Reputation: 16737

If MyStruct is an aggregate, you could use aggregate initialization to avoid defining a constructor:

myStructPtr = new MyStruct {{arg1, arg2}, {arg1, arg2}};

If not, please provide a constructor taking the appropriate arguments and call

myStructPtr = new MyStruct{arg1, arg2};

Upvotes: 3

Praetorian
Praetorian

Reputation: 109119

You're trying to use C's designated initializers, which are not part of C++. If you have a C++11 compiler, you can simply do the following:

MyStruct *myStructPtr = new MyStruct
{
    MyClass(arg1, arg2),
    MyClass(arg1, arg2)
};

Live demo

Upvotes: 2

Related Questions