web analytics

Using Constructor Intialization List in C++

Options

davegate 143 - 921
@2016-01-03 18:12:41

C++ provides a method for initializing class member variables (rather than assigning values to them after they are created) via member initializer list. The member initializer list is inserted after the constructor parameters. It begins with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma.

Using constructor initialization list will directly result in invoking the right constructor, thus saving the overhead of default constructor invocation. You should use constructor initialization list to initialize the embedded variables to the final initialization values. Assignments within the constructor body will result in lower performance as the default constructor for the embedded objects would have been invoked anyway.

In the example given below, the optimized version of the Manager constructor saves the default constructor calls for _name and _position strings.

Manager::Manager(string name, string poistion)
{

    _name = name;

    _position = position;
}


// Optimized Version

Manager::Manager(string name, string position): _name(name), _position(position)
{  
}  

Note that you no longer need to do the explicit assignments in the constructor body, since the initializer list replaces that functionality. Also note that the initializer list does not end in a semicolon.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com