Can you put an if statement in a constructor in c++ to set up an object in a particular way?

Viewed 275

I have a class that will take in 4 parameters when an object is created for it. These are: a character, and 3 integers.

However, depending on what the character is, the object needs to be set up in a different way. e.g. if the character is 'T' then set all object parameters to 0 except for those given, but if the character is 'B' then set all the class parameters to 10 except for those given.

I'd like to do this at the point of the object's creation.

Ideally, I would overload the constructor like this:

construct('B', int a, int b, int c) { //set up this way }
construct('T', int a, int b, int c) { //set up another way }

But I don't think that's allowed.

Is the best option to use an if statement inside the constructor?

construct(char letter, int a, int b, int c) {
    if (letter == 'T'){
        //set up this way
    } else {
        //set up another way
    }
}

Or, is there a better way?

Edit: For clarification, I think I remember my coputing lecturer saying that it's good practice to keep construtors short (although I might be wrong). So partly my question is; does using the if statement approach make the constructor unnecessarily long?

Edit 2: Thanks for all the help, I spoke to a lecturer and he said the same thing. An if statement is reasonable, and it only would have been a problem if I'd put in a loop. The accepted answer works but I have decided to stick to what I know.

1 Answers

You can use a discriminating token to distinguish which constructor you want to invoke. Since, otherwise, the parameters are all of the same times in the example case.

#include <iostream>

class Foo {
public:
    enum B_token{ B };
    enum T_token{ T };
    Foo(B_token, int, int, int);
    Foo(T_token, int, int, int);

    int value;
};

Foo::Foo(B_token, int a, int b, int c) : value{a + b + c} {}
Foo::Foo(T_token, int a, int b, int c) : value{a * b * c} {}

int main() {
    auto b = Foo{Foo::B, 2, 3, 4};
    auto t = Foo{Foo::T, 2, 3, 4};
    std::cout << "b:" << b.value << "\n";
    std::cout << "t:" << t.value << "\n";
}
Related