Sign in to follow this  
TheRealMAN11

c++ class constructors

Recommended Posts

In doing some reading recently I cam accross the following construct:
class MyClass
   {
   public:
   
      MyClass() : integer(23) { }

      int integer;
   };
        
What is the purpose of doing that instead of this:
class MyClass
   {
   public:
   
      MyClass() { integer = 23; }

      int integer;
   };
        

Share this post


Link to post
Share on other sites
It is called the member initialization list, and what it does is initialize your member variables at construction, as opposed to after construction. It is like:

int num = 0; (initializer list)

vs.

int num;
num = 0; (assignment after initialization to bogus value)

Initializer lists can be useful for example when you have constant member variables (which cannot be assigned a value after construction).

Regards,
jflanglois

Share this post


Link to post
Share on other sites
Quote:
Original post by TheRealMAN11
It's simular to how you call the constructor of a parent class.


Yes... and the same way you initialise 'reference' attributes

E.g.:


class foo
{
public:
foo():my_bar(a_bar),my_const_bar(c_bar){};

private:
bar& my_bar;
const bar& my_const_bar;
}

Share this post


Link to post
Share on other sites
To elaborate a bit more it's particularly useful when you have objects where the constructor and assignment operators are expensive. If you initialise the object in the constructor then the default constructor is invoked when the container is created, followed by the assignment inside the container's constructor. If you use the initialiser list only the constructor of your choice will be executed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this