How to initialize an array member in a member initializer list

How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible? Yes. It’s using a struct that contains an array. You say you already know about that, but then I don’t understand the question. That way, you do initialize … Read more

What does a colon following a C++ constructor name do? [duplicate]

This is a member initializer list, and is part of the constructor’s implementation. The constructor’s signature is: MyClass(); This means that the constructor can be called with no parameters. This makes it a default constructor, i.e., one which will be called by default when you write MyClass someObject;. The part : m_classID(-1), m_userdata(0) is called … Read more

Member initialization while using delegated constructor

When you delegate the member initialization to another constructor, there is an assumption that the other constructor initializes the object completely, including all members (i.e. including the lines member in your example). You can’t therefore initialize any of the members again. The relevant quote from the Standard is (emphasis mine): (§12.6.2/6) A mem-initializer-list can delegate … Read more

Initializing a member array in constructor initializer

How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible? Yes. It’s using a struct that contains an array. You say you already know about that, but then I don’t understand the question. That way, you do initialize … Read more

Does a const reference class member prolong the life of a temporary?

Only local const references prolong the lifespan. The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor’s argument n, and becomes invalid when the object n is bound to goes out of scope. The lifetime extension is not transitive through … Read more

What is this weird colon-member (” : “) syntax in the constructor?

Foo(int num): bar(num) This construct is called a Member Initializer List in C++. Simply said, it initializes your member bar to a value num. What is the difference between Initializing and Assignment inside a constructor? Member Initialization: Foo(int num): bar(num) {}; Member Assignment: Foo(int num) { bar = num; } There is a significant difference … Read more