Reputation: 73
struct Date1 {
int day{1};
int month{1};
int year{2000};
};
struct Date2 {
int day =1;
int month =1;
int year =2000;
};
struct Date3 {
Date() : day(1), month(1), year(2000) {}
int day;
int month;
int year;
};
Is there any difference in terms of efficiency between those three options of default initialization of the struct member?
Upvotes: 1
Views: 64
Reputation: 180424
Is there any difference in terms of efficiency between those three options of default initialization of the struct member?
No. In class member initializers are just syntactic sugar for a member initialization list so they all generate the same code.
The real benefit comes from when you have multiple constructors like
struct Date {
int day{1};
int month{1};
int year{2000};
Date(int year) : year(year) {}
Date(int year, int month) : year(year), month(month) {}
Date(int year, int month, int day) : year(year), month(month), day(day) {}
};
versus
struct Date {
int day;
int month;
int year;
Date(int year) : year(year), month(1), day(1) {}
Date(int year, int month) : year(year), month(month), day(1) {}
Date(int year, int month, int day) : year(year), month(month), day(day) {}
};
In the first case if I need to change the default day, I only need to change it in once. In the second code block I have to update it twice, so it's more work and with more work comes more chances for getting it wrong.
Upvotes: 3