c++classinitializationclass-members

C++ Is it a bad idea to initialise class members by assigning them other constructor initialised class members?


I discovered a query way of initialising a class member q by assigning it to a different class member that is initialised through the constructor i:

class test{
public:
    test(int c) : i(c) {
    }

    int i;
    int q = i;
};

int main() {
    std::cout << test(1).q << std::endl; //outputs 1
}

However if I swap around the order of declaration of i and q:

int q = i;
int i;

Printing out i outputs 0.

Is it a bad idea to initialise class members this way? Clearly in this example its probably easier to just add : i(c), q(c) to the constructor.

But for situations where there is a class member that rely on i e.g. some object with a constructor that takes a int (i) and has a private = operator and copy constructor might this approach be a good way of initialising that object? Or is this a bad idea and should always be avoided?


Solution

  • Yes, you've outlined the conditions of failure. It's not hard to imagine someone unintentionally breaking your code due to reordering.

    If you wanted to do something like this, it's best to assign both in the constructor from the input source.

    test(int c) : q(c), i(c) {}
    

    This has less confusion about initialization order and the two variables are no longer dependent.