Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the defaulted default constructor initialize variables to zero?

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;

like image 384
Chris Nolet Avatar asked Feb 05 '17 05:02

Chris Nolet


People also ask

Does default constructor initialize 0?

As default constructor initializes the data members of class to 0.

Can a constructor initialize variables to their defaults?

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.

What happens in a default 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.

Which variables are initialized to zero?

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.


2 Answers

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.

like image 66
R Sahu Avatar answered Oct 24 '22 17:10

R Sahu


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.

like image 34
M.M Avatar answered Oct 24 '22 18:10

M.M