class A {
public:
int a;
A(int x)
{
a = x;
}
};
OR
class B {
public:
int b;
B(int x):b(x){}
};
Which one would initialize the object faster ? Or will same code be generated ultimately for both and the time taken to initialize will remain the same ? Or does it depend on the compiler ?
For POD members, including
int, they will be the same, because the member won’t be constructed twice.For types with a default constructor, the second will be faster, because the first option is equivalent to:
if
ais a member of typeB(with a default constructor).Note that there are situations where you must use initializer lists:
constmembers, reference members, members of a class-type that don’t have a default constructor.POD-member:
No initializer list:
Initializer list:
i.e. identical, & that’s because
aisn’t initialized before entry to the constructor body.Non-POD member:
No initializer list:
Initializer List:
i.e. initializer list option is better.