Search code examples
c++variablesinitializationdefinition

Why separate variable definition and initialization in C++?


I'm currently working on some quite old C++ code and often find things like

int i;
i = 42;

or

Object* someObject = NULL;
someObject = new Object();

or even

Object someObject;
someObject = getTheObject();

I completely understand what this code does but I really have no idea when such a separation of variable definition and initialization could be helpful. I searched for some explanations but always ended up with member initialization lists or the question when you should define your local variables.

In the end, I don't understand the reason why someone could have intentionally written this code. It just splits definition and initialization up into two subsequent lines and creates overhead – in the last case it creates an object using the default constructor only to destroy it in the next line.

I wonder whether I should simply change the code to

int i = 42;
Object* someObject = new Object();
Object someObject = getTheObject();

Could this lead to any problems?


Solution

  • Object someObject;
    someObject = getTheObject();
    

    This uses the assignment operator.

    Object someObject = getTheObject();
    

    This uses the copy constructor.

    Apart from that, your suggested changes are equivalent, and you should implement them. The copy ctor/assignment operator difference is expected to produce the same result, this is not enforced by the language though.

    I see no valid reason to split up declaration and assignment like the original code does - even though for all practical purposes it doesn't introduce overhead (except for the object)