Reputation: 77
After reading up on C++11 and common guidelines surrounding it, I often read about how you should use in-class initialization as well as aggregate initialization.
Here's an example from what seems to be the "old" way of doing things:
class Example
{
public:
// Set "m_x" to "x", "m_y" gets set to the default value of 5
Example(int x) : m_x(x), m_y(5)
{
}
private:
int m_x;
int m_y;
};
And to my understanding this is what people recommend now:
class Example
{
public:
Example(int x) : m_x{x}
{
}
private:
int m_x{0}; // Supposedly {} works too? I guess this would
// only be necessary if I had another constructor
// taking in 0 arguments, so "m_x" doesn't go uninitialized
int m_y{5};
};
My question is: How does this affect pointers, references, and some of the STL classes? What's the best practice for those? Do they just get initialized with {}
? Additionally, should I be doing this even if the constructor initializes the variables anyway? (i.e. Writing m_x{}
even though it gets set to something else by the constructor anyway)
Thank you.
Upvotes: 0
Views: 447
Reputation: 206607
You can use in-class member initialization and delegating constructors to reduce code duplication. See my answer to a related question: Refactoring with C++ 11.
Member variables of pointer types can be initialized to nullptr
using in-class member initialization. Initializing pointers to something else using in-class member initialization does not seem to be useful. You'll have to judge it for your specific use case.
Member variables of reference types will most likely need to be initialized using the initializer list syntax. Initializing references to something else using in-class member initialization does not seem to be useful. You'll have to judge it for your specific use case.
Re. classes from the standard library ... You can certainly initialize container types using in-class member initialization. The following class is perfectly fine.
struct Foo
{
std::vector<int> ar = {20};
};
Upvotes: 1