Jimmy Scionti
Jimmy Scionti

Reputation: 77

Two different variable initializations in a C++ Class. What's the difference?

I'm a beginner self-taught, so I guess I'm going to ask something quite basic and that, yet, I ignore.

Suppose you have a class named aClass in C++ and one of the contructors requires a parameter. What's the difference between these two approaches?

1st:

aClass::aClass(int aVariable) : privateVariable(aVariable) {}

2nd:

aClass::aClass(int aVariable) {
    privateVariable = aVariable;
}

If they're basically the same thing, which of the two is more common? Alternatively, for which reason people tend to use instead of the other?

Thanks!

Upvotes: 1

Views: 64

Answers (2)

Aziuth
Aziuth

Reputation: 3902

Even though this already has an accepted answer, let's elaborate a little bit.

Let's give you an example in which one works and the other doesn't:

class Foo
{
    public:
        Foo(int value);
    private:
        Foo();
        int content;
};

class Bar
{
    public:
        Bar(int value);
    private:
        Foo foo;
};

A working implementation of the constructor would be

Bar::Bar(int value) : foo(value) {}

If however you would go like

Bar::Bar(int value) 
{
    foo = Foo(value);
}

What would happen is that this would not compile. As a demonstration, I created http://cpp.sh/2vfwqk, see what happens if you try to run it. Then un-comment the lower implementation and out-comment the one above.
Thing is, Foo() would have to be called before it can start to handle the body, as foo needs to be initialized.
And an initializer list does that directly.

(The example would also work if instead of making the empty constructor private I had completely omitted it, but like this it is easier to understand.)

Another thing is that if Foo() would be public, it would construct two objects. If those are lightweight, no problem, but if the empty constructor requires high amount of memory or time, undesireable.

And you pretty much need this for members that are references.
Maybe a worthwhile read for you: https://www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c/

Upvotes: 2

Jarod42
Jarod42

Reputation: 218323

The first one does initialization and should be preferred.

The second one does assignment (after default initialization). it is mostly equivalent to:

aClass::aClass(int aVariable) : privateVariable() {
    privateVariable = aVariable;
}

So doesn't work if privateVariable is not default constructible.

Upvotes: 3

Related Questions