What's the difference between initializing the object member variable m_A
in-class (class B
) versus in an initializer list (class C
)? Is one method more efficient or generally preferred over the other?
class A
{
public:
A(int num) { m_Int = num; }
private:
int m_Int;
};
class B
{
private:
A m_A{10};
};
class C
{
public:
C(): m_A(10) {};
private:
A m_A;
};
Is one method more efficient
No, not if you measure efficiency in CPU cycles. One may be more efficient in other ways, like, being visible in a header file compared to be hidden inside an implementation. Efficiency could then be measured in how long it takes for another programmer to understand the default.
... or generally preferred over the other?
In-class initialization may be preferred in situations when you'd never want to be able to construct an object with member variables in an uninitialized state. On the other hand, if you don't want (costly) initialization that your class will do later, if needed, you'd go for the initializer list in the constructor(s) that actually will initialize the member variable(s). There's no right or wrong.