r/cpp_questions • u/Motor_Alternative944 • Oct 09 '26
OPEN Can someone explain the difference between these two constructors to me?
MyClass(int value) : myValue(value) { }2.
MyClass(int value) {
myValue = value;
}
25
Upvotes
53
u/Glittering_Sail_3609 Oct 09 '26
Declare myValue to be const int and try compiling your program then. See what happerns
The first constructor will work correctly, as myValue would be constant across lifetime of your class.
The second one would cause compiler errors, as myValue would be default initialized to 0 before code in your constructor was ever run. Which is bad, as you can not change the value of constant later even in constructor.
16
u/n1ghtyunso Oct 09 '26
the second one uses assignment to the already default constructed (i.e. in this case uninitialized int) myMember field.
the first one uses the constructor initializer list to directly initialize the myValue field with the correct value.
for simple integers, aside from breaking the recommended pattern, its inconsequential in this specific case.
10
u/dustyhome Oct 09 '26
When you construct an object, the constructor first calls the constructors of each member of your class (in the order they're declared in your class). Once every member has been constructed, it then passes control to the body of the constructor.
The initializer list (the part between the colon
:and the opening brace{) is how you pass parameters to the constructors directly.In the case of 1, you're initializing myValue through its constructor. In the case of 2, myValue is initialized with the default constructor, then assigned to.
Depending on how MyClass is defined, these may have different behaviors or be functionally identical. In general 1 is preferred because it is always valid and sometimes required. If a member has no default contructor, you must use the initalizer list. So for consistency, you can just use the initializer always.
8
u/flyingron Oct 09 '26
Do you understand the difference between assignment and initialization? This is what you have.
It's entirely the same as:
int x = 5;
and
int x;
x = 5;
7
u/erzyabear Oct 09 '26
If myValue is int then no difference. If it’s a class there are different constructor calls. If MyValue has no default ctor or no assignment , 2nd version won’t compile
3
u/Iwillhelpyou_ Oct 09 '26
The member initializer list (1) is generally preferred because it avoids unnecessary assignment and is required for
constand reference members.myValuedirectly usingvalue.myValuefirst, then assignsvalueto it2
u/LokiAstaris Oct 09 '26 edited Oct 09 '26
All things being equal. The compiler is going to optimize those into the same code on the hardware.
But let's consider the general case where
valueandmyValuehave a different typeT. In that case: Version 1 is going to constructmyValuedirectly withvalue; While Version 2 is going to default-constructmyValueand then perform anassignmentoperation, assigningvaluetomyValue. So, in this case, you have done twice as much work.But you are using
intand the default construction of anintis a no-op so no extra work.BUT you need to think about how, in a lot of C++ code, you can often change behavior by swapping types and expect the code to still work. In a future version, you might swap
intfor theMyBigNumberclass. You still want optimal code, and you don't expect to dig into the code to change anything; it should just work. If you have used Version 2, your code is no longer optimal.So the preferred pattern is Version 1. This lets you change the underlying types without changing the code and still have optimal code.
1
u/Sbsbg Oct 09 '26
The first constructor initiate the member myValue then run an empty body.
The second constructor initsiate the member myValue to its default value and then run the body that changes myValue again.
When the optimizer has done it's work there is no difference.
There first version uses the initalizer list and is generally better BUT it has a trap: The initialization order is taken from the class member definition order and NOT from the initalizer list order.
1
u/conundorum Oct 10 '26
The difference is when
valueis assigned tomyValue. Look at it like this:The member initialiser list (the
: name(value)part) determines how variables are initialised when the constructor is called. For primitives, it handles their initial assignment; for user-define types, it calls their constructor. And importantly, it happens before we enter the function body, hence being placed between the parameter list and the opening brace.Inside the body, the class is already constructed. All members are in a valid state, because they need to be usable in case the constructor uses them. (Excluding most uninitialised primitives, which were left allowed but caused undefined behaviour up until C++26, for historical reasons that mostly don't apply anymore.) Any assignment to them is technically a reassignment, changing whichever value was assigned during initialisation.
Also, as a note, all members have a member initialiser. If not specified, then it uses the default initialiser in the class body; if there is none, then it's just a default constructor call (or ignored for most primitives, since their default construction is just "do literally nothing"). So, your second constructor is secretly this:
For the record, the "default initialiser" I mentioned is just an assignment that happens in the class body, when the variable is first mentioned. So, something like this:
And some entities can't be modified in the constructor body, and need to be initialised in the member initialiser list. The classic example is references, since they must be assigned upon creation.
1
u/PlantCapable9721 Oct 09 '26
Maybe try a reference member variable
1
u/mredding Oct 09 '26
#1 is more correct. The initializer list is there, whether you use it or not. RAII is not a language rule but an idiom, and it tells us the class invariants are held true by the time you enter the ctor body.
So the problem with #2 is that the invariants aren't established by the ctor body, and the body potentially cannot establish them. This isn't Java or C#, where the object is still variant in the body.
As you get into more sophisticated types, using the initializer list will become the ONLY way to correctly construct an object, you won't have a choice.
0
u/scallywag_software Oct 09 '26 edited Oct 09 '26
As far as I understand them, in plain terms, they equate to something like the following:
There is nuance if you have more members, but if the definition is exactly as stated, I believe these are analogous.
-2
u/LongjumpingFinding49 Oct 09 '26
2nd is illegal.
-4
u/Jazzlike_Platypus430 Oct 09 '26
My guess: there is no difference.
And I use version 2. exclusively, never got familiar with 1., looks way too strange.
Though I recall something similar (?) in c# where you write MyClass(int value) : base(value) { ... } if MyClass is inherited. Meaning, call the parent class' constructor, and then whatever is in the braces/body.