Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference in class member initialization C++11

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;
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading