Friday 24 February 2012

Can we use initialization lists or assignments in a constructor? | C++

The constructor uses initialization lists. In fact, all the member objects in the initialization list should be initialized by a constructor. Let's take an example of One exception.
Consider the following constructor that initializes member object r__ using an initialization list: Harry::Harry() : "-(whatever) { }. This results in the improved performance. For example, if a member variable r_ is of the same type as the whatever expression, then the compiler do not have to make a separate copy of the object and the outcome related to the whatever expression is constructed directly inside r_.
Even if the types are not same, the compiler is able to initialize objects with initialization lists, even if the types are different than assignments.
Assignment is another way of building constructors, such as, Jimmy::Jimmy() { j_ = whatever; }. In this case, the temporary and separate objects are created as a result of the expression whatever and the temporary object is passed into the jL object's assignment operator.
By the use of an assignment operator in a constructor, the default constructor has fully constructed the member object and results in the allocation of some amount of memory by default or the opening of some default file. The major drawback of using the assignment operator is that all the work done may be lost if the whatever expression or the object of the assignment operator closes the particular file or release that memory. For example, if a wrong file is opened.