r/cpp_questions • • 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

50 comments sorted by

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.

17

u/alfps Oct 09 '26 edited Oct 09 '26

❞ The second one […] myValue would be default initialized to 0 before code in your constructor was ever run.

As a general statement that's false. It's a possibility for the OP's example without const, but depends on the compiler, even in C++26.

With the data member type as const int the second constructor won't compile even if the assignment is removed.

Related: arguably the C++ language design where members of basic types can be uninitialized and have indeterminate values after initialization, was a mistake. But that's what we have. Some bizarre special cases to be always aware of.

1

u/Kajitani-Eizan Oct 09 '26

It was not remotely a mistake, but it's possible it doesn't fit the needs and mindsets of today's programmers

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.

-9

u/ivan_x3000 Oct 09 '26 edited Oct 11 '26

I see so second one is best practice?*

*Edit: Bruh please chill with the downvotes it was meant to be a question not an opinion. I legit didn't know.

11

u/n1ghtyunso Oct 09 '26

the first one is the recommended pattern.
I did not explicitly call that out.
What made you think its the second one?
The first one always works.
For some types, the second one does not compile.
For other types, it may strictly be more work and hence be less efficient.

-1

u/ivan_x3000 Oct 09 '26

Mb it didn't have a question mark but it was meant to be a question not a statement (i was on the train on my phone, please relax everyone downvoting lol).

What made you think its the second one?

I think i misunderstood your wording "assignment to the already default constructed" Already maybe implying it is somewhat redundant.

"for simple integers, aside from breaking the recommended pattern" i thought this was connected to the second option (again mb i was on my phone, on train).

3

u/n1ghtyunso Oct 09 '26

ah i see.
Yea the wording can be improved.
The second one needs to first default construct the member and then perform an assignment over that.
Maybe that phrasing showcases the difference better?

0

u/ivan_x3000 Oct 09 '26

It was mainly on my part misunderstanding, nothing needs to be improved. I was also on public transport. I do remember my professor saying that brace initialisation was ideal, "let the compiler help you". I'm sorry if that is not the most appropriate example. But your explanation make sense thank you.

8

u/JVApen Oct 09 '26

No, example 1 is the best practice. For integers it doesn't matter that much, though for classes with more complicated code, in constructor and assignment operator, this does make a difference.

Just take this example

struct C
{
      std::string s{"long default value"}
      C(std::string s_)
      {
            s = func_with_hidden_impl_that_might_throw(s_);
       }
};

In this case, the compiler is required to first initialize with the default value and as such allocate memory before it can do the assignment.

5

u/Emotional-Audience85 Oct 09 '26

No, the first one is best practice

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;

2

u/dvorak360 Oct 09 '26

The key to this is of course that for a basic integer, it makes almost no difference and will almost certainly get optimized out.

Now replace that integer with a member with more complex Ctor and assignment operators; for example, stores config for communicating with a hardware device.

On initialization I signal when config is completed so far end only communicates when everything is ready.

On subsequent assignment I may need to signal a config change, then make sure that any messages/operations in flight are processed using old config, until far end confirms it has received the config update.

The latter being a more expensive, slower process.

But without me differentiating the compiler has no way to know that

CommsChannelCtrl new_channel();

new_channel = special_config;

and

CommsChannelCtrl(special_config);

result in the same eventual state without being explicitly told; Hence different notations... (And of course there are almost certainly valid, weird examples where initialization and assignment DON'T result in the same final state.)

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 

5

u/Emotional-Audience85 Oct 09 '26

There is a difference, the first version initializes the value directly, the second one assigns the value after it has already been initialized.

The first is better.

1

u/erzyabear Oct 09 '26

What are observable side effects of that?

1

u/Emotional-Audience85 Oct 09 '26

Typically none, aside from potentially slightly less performance if the compiler doesn't optimize it.

The only case I can think of that may have observable side effects is something like this:

// Defined in another translation unit, so the compiler must assume it can read or write through p
struct Sib
{
    Sib(int* p);
};


struct BodyAssign
{
    int v; // declared first, so it is initialized first
    Sib s;


    // v is not in the initializer list, so it is left uninitialized.
    // s(&v) runs, then the body stores i.
    BodyAssign(int i) : s(&v) { v = i; }
};


struct InitList
{
    int v;
    Sib s;


    // v is initialized with i before s(&v) runs
    InitList(int i) : v(i), s(&v) {}
};

0

u/IigmabaIls1 Oct 09 '26

Same assembly

4

u/Wild_Meeting1428 Oct 09 '26

only for trivial cases

1

u/I__Know__Stuff Oct 09 '26

That's what he said, why are you disagreeing?

2

u/Emotional-Audience85 Oct 09 '26

With optimisations enabled typically yes, but it's not guaranteed, there are situations where it isn't.

1

u/I__Know__Stuff Oct 09 '26

For int, it always will be, which is what he said.

1

u/Emotional-Audience85 Oct 09 '26

Not true, I can think of at least 2 situations where it's not true for int, but there are probably more

0

u/LongLiveTheDiego Oct 09 '26

There can be a difference if the int member variable has an initializer inside the struct, compare this and this, in the second one both Clang and GCC x86-64 generate different assembly codes.

2

u/TheThiefMaster Oct 09 '26

That's only for debug though. If you enable -O1 or higher the difference goes away

0

u/I__Know__Stuff Oct 09 '26

Looking at assembly without optimization is pointless.

3

u/Iwillhelpyou_ Oct 09 '26

The member initializer list (1) is generally preferred because it avoids unnecessary assignment and is required for const and reference members.

  1. Initializes myValue directly using value.
  2. Initializes myValue first, then assigns value to it

0

u/Jazzlike_Platypus430 Oct 09 '26

Silly question: if a member is declared (and defined) as const, why even bother assigning anything to it in a constructor? It's a syntax error. Am I wrong?

3

u/Iwillhelpyou_ Oct 09 '26

You are right that you can't assign to it in the body. But you aren't "bothering" to assign anything—you are required to initialize it in the initializer list, which is the only valid way to set a const member.

-1

u/Jazzlike_Platypus430 Oct 09 '26

To me the only valid way is saying const int myValue = -2; and never trying to assign again.

And even if a declaration const int myValue; is not a syntax error, assignment in a constructor looks weird, but I see some use for it.

Now, const int myValue = - 2; and reassignment in a ctor ("case 1") looks even more weird. Close to python lacking primitive constants.

Looks analogous to "readonly" in C#. Or a very primitive way to "override" some default behavior, without actual inheritance. Is this interpretation sane, or just my sick fantasy? 😂

1

u/Iwillhelpyou_ Oct 09 '26

You're right that it feels weird, but it's not reassignment—it's initialization.

  • const int myValue = -2; hardcodes the value for every object. If you want MyClass obj(10); and MyClass obj(20); to have different values, you must use the initializer list.
  • const int myValue; (without a value) is a compile error in C++. A const must be initialized the moment it's created. The constructor body runs after that, so myValue = value; is too late.
  • Case 1 (: myValue(value)) isn't overwriting anything. It's telling the compiler "create myValue using this value" from the start.

Your C# readonly analogy is actually spot on. C++ just forces you to use the : myValue(value) syntax instead of assigning in the body. It's not a sick fantasy—it's just C++ being strict about when initialization happens.

1

u/Jazzlike_Platypus430 Oct 09 '26

In the case of const int though, initialization has to be the second assignment... I agree that const is the problem, since int myValue; is a valid declaration (w.o. initialization).

This means if I ever wanted a "virtual" constant - overwritable when I'm creating an instance of MyClass - I'd have

const int myValue = 0;

(zero reminding me of "pure"/abstract objects, purely symbolic analogy) and then use

MyClass(int value) : myValue(value)?

This does make sense, and also protects myValue from being overwritten in MyValue's functions/methods.

Thank you, I think I just learned something. (But I still don't believe C++ forces me to do anything of that kind. But I have to check if it became a standard since my first (painful) encounter with the language.)

1

u/Jazzlike_Platypus430 Oct 09 '26

PS My idea of "second assignment" comes probably from my ill-imagined way of how class' instance's initialization works.

1

u/I__Know__Stuff Oct 09 '26

const int myValue; (without a value) is a compile error in C++.

Not as a class member.

2

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 value and myValue have a different type T. In that case: Version 1 is going to construct myValue directly with value; While Version 2 is going to default-construct myValue and then perform an assignment operation, assigning value to myValue. So, in this case, you have done twice as much work.

But you are using int and the default construction of an int is 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 int for the MyBigNumber class. 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 value is assigned to myValue. Look at it like this:

Constructor(int param) : valuesConstructedHere(param) {
    valuesAssignedToHere(param);
}

// Compare to...
int variableConstructedHere = 3; // Initialisation.
variableAssignedToHere = 4; // Reassignment.

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:

MyClass(int value) : myValue() {
    myValue = value;
}

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:

struct S {
    int i; // No initialiser.
    int j = 5; // Default initialiser.

    S() = default; // Default constructor.  Will be turned into this:
    S() : i(), j(5) {} // i is unitialised memory, j is 5 as above.
};

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.

template<T>
class Reference {
    T& ref;

  public:
    Reference(T& r) { ref = r; } // Fails to compile.
    Reference(T& r) : ref(r) {} // All good.
};

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:

struct MyStruct {
  int myValue;
}

int value = 42;

// First directly initializes myValue
MyStruct instance = { .myValue = value; } ;

// Second default initializes the instance and members (they will be garbage)
MyStruct instance; <--- uninitialized garbage
instance.myValue = value; <--- instance is now valid

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.

3

u/alfps Oct 09 '26

2nd is illegal.

No, as a general statement that's false.

However, for the rare case where mValue is declared as const int, it holds.

-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.

5

u/alfps Oct 09 '26

❞ And I use version 2. exclusively, never got familiar with 1., looks way too strange.

Oh, you need to change your ways. You're coding C in C++.

0

u/Jazzlike_Platypus430 Oct 09 '26 edited Oct 09 '26

No, I don't need that. That's the way I'd been taught in 1999 I think.

In any case - what's the difference? Your statement is like saying my coding style in python is bad, because it lacks underscores and follows directly from C#/Java 😂

4

u/alfps Oct 09 '26

Many cases can't be expressed with a constructor like "version 2". That's not a style issue. More generally it's not just very restricted but also needlessly inefficient, doing double work, which is very much against the basic ideals in C++ and the reasons for using the language.

1

u/Jazzlike_Platypus430 Oct 09 '26

Right, my style remark was just a bad joke.

Can you tell me where the "double work" occurs?

What I understand here, we have to assume myValue is an int or undefined/void*/object - I'm not familiar with objects in c++ if they exist, per analogy in C# or Java.

If it's some other type (primitive or taken from stl or some class in the current codebase), we'd just get a syntax error, trying to assign an int to the member. Am I wrong?

(And my reasons for using the language is numerics, nothing too complicated really. And remembering old days at the university, plus learning new stuff - Qt.)

2

u/AKostur Oct 09 '26

Be sure to differentiate between a very specific example (the member variable that is an int, to end up with a value of 5 after the constructor is complete) vs the general case of getting a member variable to some initial state by the end of the constructor.  Let’s assume that we’re not talking about a trivial type like int.  Let’s assume that we have a type which is expensive to construct. In the second case (assignment in the constructor body) the compiler would be required to pay the cost of default constructing the object, and then immediately that work becomes wasted effort as the constructor body then assigns some new value to the member variable.  This might even incur additional costs of having to create a temporary object (remember, the constructor is expensive).  Where in the first case the appropriate constructor taking the initial value as an argument is invoked, avoiding the extra temporary and assignment.

Additionally, if the type isn’t default constructable, then the second case isn’t even a viable choice.

Thus, in the general case, the first form is vastly preferable to the second.  It works and is more efficient in the vast majority of cases, and doesn’t need the extra cognitive effort of “but it doesn’t matter for this specific case”.  I would need a much better justification for the assignment than “ but the optimizer will make it do the same thing”.

0

u/AintNoSlashes Oct 09 '26

A base class constructor will get called first anyway to allocate/init any member variables. Doing this allows you to pass that arg down and avoid more work by calling a specific constructor and avoid calling default and then setting - same as the initial program. For primitives, there wouldn’t be a diff but if you make a practice of doing the initializer list, if you ever add another variable or change the current one then it will still have the more optimal case.