In his book "Programming, Principles and practices using C++" Bjarne Stroustrup introduces the concept of member initializer list on pages 314-316 (§ 9.4.4). He uses the following example:
// Simple Date (year, month, day)
class Date
{
public:
Date(int yy, int mm, int dd): y{yy}, m{mm}, d{dd}
{
//...
}
private:
int y, m, d;
};
On page 315 he says:
We could have written:
Date::Date(int yy, int mm, int dd) // constructor { y = yy; m = mm; d = dd; }
but then we would in principle first have default initialized the members and then assigned values to them.
Therefore, can I conclude that using member initializer lists makes the code slightly faster? Of course, no one would notice on a modern PC. But I'm planning to use C++ for embedded development.
EDIT:
I'll further specify my question. By "slightly faster" I actually mean "less CPU cycles involved".
I also agree that the potential efficiency increase for this particular example will be near to nothing. But for much larger classes and structs, it might become noticable on a microcontroller.
In the second example you are not initializing, you are assigning to variables which have been already initialized. The variables are initialized (default constructed) before entering the constructor, so you are actually setting them twice.
An int
doesn't have any specific default initializer so you don't notice but try with different code as in
#include <iostream>
using namespace std;
class Foo
{
int x;
public:
Foo() : x(0) { cout << "Foo()" << endl; }
Foo(int x) : x(x) { cout << "Foo(int)" << endl; }
Foo& operator=(const Foo& o) {
cout << "Foo::operator=(const Foo&)" << endl;
this->x = o.x; return *this;
}
};
class Bar
{
Foo foo;
public:
Bar(const Foo& foo) { this->foo = foo; }
Bar(bool, const Foo& foo) : foo(foo) { }
};
int main() {
cout << "Assigned in constructor" << endl;
Bar bar = Bar(Foo(5));
cout << "Assigned in initializer list" << endl;
Bar bar2 = Bar(false, Foo(5));
}
This prints
Assigned in constructor
Foo(int)
Foo()
Foo::operator=(const Foo&)
Assigned in initializer list
Foo(int)
so you see they're definitely not equivalent. Indeed, for example, you are not able to assign a const
field in a constructor