0
#include <iostream>
#include <string>

class Data
{
    private:
    int day, month, year;
    public:
    Data() : Data(0,0,0) {};
    Data(int d, int m, int y) : day(d) , month(m), year(y) {}
    void print() { std::cout << day << " " << month << " "<< year << std::endl; }
};

int main()
{
    Data a;
    a.print(); //ok - output: 0,0,0 and no compiler errors
}

A constructor does not have a returning value, and a constructor is called when an object is created, meaning the data can be initialized, so when I call a constructor from another constructor, is this completely valid?

I've also noticed that Data() { Data(0,0,0); }; does NOT initialize the current class data members.

Why is it that Data() : Data(0,0,0) {}; works and Data() { Data(0,0,0); }; does not?

Vinícius
  • 15,498
  • 3
  • 29
  • 53
  • 3
    Check out [delegating constructors](http://en.cppreference.com/w/cpp/language/initializer_list#Delegating_constructor). Your second example just creates an unnamed temp on the stack and destroys it. Its got nothing to do with construction. – Mike Vine May 15 '17 at 16:13

1 Answers1

0

It is perfect practice to do perform:

Data() : Data(0,0,0) {};

You are simply calling utilizing your initializer list.

The reason

Data() {
    Data(0,0,0);
}

does no work is because all you have done is created an "anonymous" Data object on the stack within the Constructor which will be destructed as soon as the default constructor is completed.

jiveturkey
  • 2,484
  • 1
  • 23
  • 41