Chris
Chris

Reputation: 31284

C++: construct by return within constructor

Suppose I have several objects with a C-style constructor:

struct MyStruct { int item1; int item2 };
MyStruct construct_struct(int a, int b, int c, ...);

And I would like, without totally rearranging code copying and pasting duplicate code, to simply define beneath the structures a C++ style constructor:

MyStruct::MyStruct(int a, int b, int c, ...){   
    // in pseudo code
    this = construct_struct(a,b,c,...);
}

How can this be done in C++?

Upvotes: 2

Views: 92

Answers (3)

If you don't want to do what dasblinkenlight suggested (even though you should). The approach in your own answer would also work so long as you object is assignable. For the unlikely case of your object getting a const member, or being made unassignable for another reason, I present this for completeness.

You can delegate to the copy/move constructor:

MyStruct construct_struct(int a, int b, int c, ...){
}

MyStruct::MyStruct(int a, int b, int c, ...) : MyStruct(construct_struct(a,b,c,...)) {}

Upvotes: 1

Chris
Chris

Reputation: 31284

The simple answer is:

MyStruct construct_struct(int a, int b, int c, ...){
}
MyStruct::MyStruct(int a, int b, int c, ...){
    *this = construct_struct(a,b,c,...);
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

I would like, without totally rearranging code copying and pasting duplicate code, to simply define beneath the structures a C++ style constructor

Rather than copying the code, you should move it into the C++ constructor, and then rewrite your C-style constructor to call the C++ one:

MyStruct::MyStruct(int a, int b, int c, ...){   
    // the code from construct_struct(a,b,c,...) goes here
}

MyStruct construct_struct(int a, int b, int c, ...) {
    return MyStruct(a, b, c, ...);
}

This solves the problem with code duplication, and preserves the C constructor.

Upvotes: 5

Related Questions