Is it good practice to initialize a member variable of a class in the header file?

Viewed 1620

Let's say I have a pointer and I want it to be initialized to nullptr. Which option would be better, to create a constructor that sets that member variable to nullptr or just initialize it in the declaration on the header file to nullptr.

Is there any differences at all? Is the latter considered bad practice?

Thanks in advance.

2 Answers

Initializing a member in the class body is completely equivalent to doing it in the member initializer list in the construcor. (But if you provide initializers in both places, member-init-list overrides initializers in class body.)

Initializing in the class body whenever possible is a good practice, because it's less error prone (you'll immediately notice if you forget to initialize a newly added member; see DRY).

If I understood your question correctly, this link should give you some information : CPPCoreGuidelines

C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead

Reason

Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.

Example, bad

class X1 { // BAD: doesn't use member initializers

    string s;
    int i;
public:
    X1() :s{"default"}, i{1} { }
    // ...
};

Example

class X2 {
    string s = "default";
    int i = 1;
public:
    // use compiler-generated default constructor
    // ...
};

Enforcement

(Simple) A default constructor should do more than just initialize member variables with constants.

Related