Tuesday, December 5, 2023

Advantages of using an initialization list : OOP in C++

There are two different methods we can use when wtriting a constructor for a C++ class. Most of  newbies to C++ have a problem of what is the difference of these two methords or is there no difference between these two. Some people ask what does that wierd colon (" : ") syntax in the C++ construstor.

These two ways are known as constructor with an initialization list and constructor without an initialization list.



Example 1: constructor with an initialization list 

Example 2: constructor without an initialization list

Values given after the colon is known as initialization list. If there are multiple values, we can provide a comma seperated list of values as initialization list.

Example 3: initialization list of multiple values.

In first example C++ initialize property "age" with the value x where the second example initialize property "age" with it's default constructor. that means if the property is an integer value it will be initialized with an undefined value.

In first example what C++ does under the hood is,
int price = x;

In the second example it is as follows,

int price;
price = x;

Lets see what are the advantages of using an initialiation list with constructor over the none initialization list way.
  • It helps to keep the code clean and less code in constructor. So we can implement important functionalities in constructor body.
  • In above example there is no significant amout of runtime improvement. But if the age is a complex object, with a heavy construction cost there can be an advantage with runtime. 
  • If we have constant attributes in class, using initialization list is the only way of initializing those values since other ways would give errors. 


No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...