Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Whats the difference between member initializing and assignment while constructing?

0
Posted

Whats the difference between member initializing and assignment while constructing?

0

First of all, be clear on what “member initializing” is. It is accomplished through a member initializer list. It is “spelled” by putting a colon and one or more constructor style initializers after the right parenthesis of the constructor: struct xyz { int i; xyz() : i(99) { } // Style A }; xyz x; will initialize x.i to 99. The issue on the table here is what’s the difference between that and doing this: struct abc { int i; abc() { i = 99; } // Style B }; Well, if the member is a const, then style B cannot possibly work: struct HasAConstMember { const int ci; HasAConstMember() { ci = 99; } // not possible }; since you cannot assign to a const. Similarly, if a member is a reference, it needs to be bound to something: struct HasARefMember { int &ri; HasARefMember() { ri = SomeInt; } // nope }; This does not bind SomeInt to ri (nor does it (re)bind ri to SomeInt) but instead assigns SomeInt to whatever ri is a reference to. But wait, ri is not a reference to anything here yet, and that’s

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123