Ahmed A
Ahmed A

Reputation: 3652

Class POD member variable initialization

Regarding the following two ways to initialize the POD member members variables:

class Trie {
  Trie()
    : isWord_(false)
  { }


  vector<Trie *> child(keyLength);
  bool isWord;
};

// OR 

class Trie {
  Trie();

  vector<Trie *> child(keyLength);
  bool isWord = false;
};

Are the two equivalent (performance wise, generated code size wise, etc)? Is there a current preference?

Upvotes: 0

Views: 141

Answers (1)

Gettor
Gettor

Reputation: 51

I would refer to this article Get to Know the New C++11 Initialization Forms for answers.

They are semantically equivalent, as the article states:

Regardless of the initialization form used, the compiler conceptually transforms every class member initializer into a corresponding mem-init

However there are some things that are allowed by second option which are impossible for first one if we go outside of POD scope. For example: array initialization.

As for current preference, there is always a strong argument of making Your code readable for others:

  • If You're working on a big project, stick to whatever form the rest of project follows, don't enforce new ideas where they're not wanted
  • If Your project is small, try to talk with other of its end-users to agree on common form if You think one is more readable than other.

My personal preference would still be first option, because with it I have all the information about class initialization in one place (the constructor) and don't have to scroll all the way to the bottom to see if someone suddenly made a default initialization there.

Upvotes: 1

Related Questions