Jump to content
  • Advertisement
Sign in to follow this  
Alpha_ProgDes

C++: Initialize in constructor vs. initializer list

This topic is 3660 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Which one is correct? Or why should I use one over the other? Example:
class Foo
{
   public:
      
      Foo(int opd, int opd2, char opr)
         : operand(opd), operand2(opd2), operator(opr)
      {

      }
}; //initializer list

class Bar
{
   public:

      Bar(int opd, int opd2, int opr)
      {
         operand = opd;
         operand2 = opd2;
         operator = opr;
      }
}; //constructor

Share this post


Link to post
Share on other sites
Advertisement
For ints it doesn't matter. For class types, use the initializer list, which will use the appropriate constructor directly. Assigning inside the constructor body will instead default construct the object and then assign to it, which is generally less efficient.

Share this post


Link to post
Share on other sites
I always like to use the initializer list. I wish I could give a more concrete reasoning as to why. It probably has to do with something Herb Sutter wrote, but I cant quite remember :)

For the record you have to use the initializer list in these scenarios:

- Initialize const members
- Initialize reference members
- Call base class constructors
- Initialize data members which have non-default constructors.

Share this post


Link to post
Share on other sites
Both is correct, but initializer list may be faster as the member doesn't get default initialized before your assignment, your compiler may however optimize that away.

I tend to use initializer list for simple assignments, like 0 to a pointer etc and assignment in the constructor for things (to me) is more complex or something that requires more setup, like new'ing a shared_ptr and then setting up the new'd class.

Share this post


Link to post
Share on other sites
You should prefer initialisation lists over the assignment in the constructor.
One reason is to avoid unnecessary default constructor calls on more complex objects. By using initialisation lists you would be constructing the objects via copy constructors.
More reasons to use them and the exceptions are explained more accurately here.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!