Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing in constructors, best practice?

Tags:

c++

I've been programming in C++ a while and I've used both methods:

class Stuff {
public:
     Stuff( int nr ) : n( nr ) { }
private:
     int n;
}

Or

class Stuff {
public:
     Stuff( int nr ) { 
         n = nr;
     }
private:
     int n;
}

Note: This is not the same as this, similar but not the same.

What is considered best practice?

like image 447
Jonas Avatar asked Mar 31 '09 17:03

Jonas


People also ask

Should I initialize in constructor?

If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.

Can we initialize object in constructor?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

Why is it best practice to initialize your variables?

Initialize Variables When Declaring Them It's a good idea to initialize our variables or constants with values when declaring them. It prevents undefined value errors, and we can both declare the variable or constant and set an initial value to it all in one line.

What is constructor initialization?

Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.


2 Answers

Initializer lists are preferred. See FAQ 10.6

like image 84
dirkgently Avatar answered Sep 17 '22 13:09

dirkgently


One big advantage to using initializers: If an exception is thrown anywhere within the initializer list, the destructors will be called for those members that had already been initialized -- and only for those members.

When you use the contructor body to initialize the object, it's up to you to handle exceptions properly and unwind the object as appropriate. This is usually much harder to get right.

like image 32
Dan Breslau Avatar answered Sep 20 '22 13:09

Dan Breslau