Search code examples
c++constructorc++14

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;


Solution

  • 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.