Dmitry Dmitry - 2 months ago 5
C++ Question

Is there a difference between "my_constructor : variable(x)" and "this.variable = x" in constructor?

Is there a difference between Demo1 and Demo2 in the following code?

#include <iostream>

class Base {};

class Demo1 : public Base {
public:
Demo1() : instance_variable(5) {

}

int instance_variable;
};

class Demo2 : public Base {
public:
Demo2() {
this->instance_variable = 5;
}

int instance_variable;
};

int main(int argc, char **argv)
{
Demo1 a;
Demo2 b;

std::cout << "a.instance_variable: " << a.instance_variable << std::endl;
std::cout << "b.instance_variable: " << b.instance_variable << std::endl;

return 0;
}


I saw the first notation in a book I am reading right now, and I am not sure if the two are equivalent or if Demo1 has subtle differences I should be aware of.

I find the second much more readable as I am coming from a Java/JavaScript background, so I am curious if I can replace "Demo1" with "Demo2" without changing the meaning of the code.

Also, what is the expression "constructor:field(x){}" called?

Answer

If you have a programming background (as you said, you have), you should be well aware of the difference between initializing value to variable and assignment of a value to some variable.

Demo1 is using the variable initialization (instance_variable is being initialized in the member initializer list, Demo() : instance_variable(5)), but Demo2 is assigning value to the instance_variable

I am not sure if the two are equivalent or if Demo1 has subtle differences I should be aware of.

No. The two aren't equivalent.

  • Demo1 is initializing the instance_variable, it means copy constructor will be called (in the case, when instance_variable is object).
  • But the Demo2 is assigning value to the variable after it has been initialized (default constructor has been called, and now operator= will be called to copy values)

Also, what is the expression constructor:field(x){} called?

It's called member initializer list.

EDIT

Member initializer list only makes a difference when initializing objects, but in case of primitives, they're pretty much the same.

And there's another thing that you should know, is, that you'll have to use member initializer list to initialize const data members, and member reference variables, and when passing parameters to base class constructor.

Comments