I'm updating a class to C++14, and trying to figure out the simplest way to initialize all of the instance variables to zero on construction. Here's what I have so far:
class MyClass {
public:
int var;
float* ptr;
double array[3];
MyStruct data;
unique_ptr<MyStruct> smart_ptr;
MyClass() = default;
~MyClass() = default;
}
Is setting the constructor to default
the equivalent of doing:
MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}
... or do I need to init each variable? (I've tried both in Visual Studio and I get zeros either way, but I'm not sure if that's luck or not.)
I'm instancing the class without brackets: MyClass obj;
As default constructor initializes the data members of class to 0.
If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.
In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body.
Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.
Is setting the constructor to default the equivalent of doing:
MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}
No. It is not.
The line
MyClass() = default;
is more akin to but not exactly equivalent to:
MyClass() {}
In either case, using
MyClass obj;
results in a default-initialized object whose members are default initialized.
However, the difference between them when using
MyClass obj{};
is that obj
will be zero-initialized with the defaulted default constructor while it will be still default initialized with the user provided default constructor.
To make all of your variables zero-initialized on construction, even if the creator did not request it, one way is:
struct MyClassMembers
{
int var;
float* ptr;
double array[3];
MyStruct data;
unique_ptr<MyStruct> smart_ptr;
};
struct MyClass : MyClassMembers
{
MyClass(): MyClassMembers{} {}
};
Then MyClass m;
will use MyClassMembers{}
to initialize the members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With