When instantiating objects, constructors often handle the initialization of member variables. For such members, an initialization list for constructors provides an abbreviated and efficient way of their initialization before the constructor’s body is executed. Apart from performance, sometimes it also compulsory because of const variables or members of a base class.
What is a Constructor Initialization List?
A constructor initialization list is a procedure to initialize member variables directly, hence, there is no default constructor that is copied and then assigned.
Syntax
The following syntax of initialization of constructor list is as follows−
ClassName(type1 param1, type2 param2):member1(param1),member2(param2){// Constructor body}
Here, member1 and member2 are initialized with param1 and param2 before the constructor body runs.
Example of Constructor Initialization List
Heres a simple example demonstrating how to use an initialization list.
#include <iostream>#include <string>classStudent{public:Student(const std::string& name,int age):name(name),age(age){}voiddisplay()const{
std::cout <<"Name: "<< name <<", Age: "<< age <<"\n";}private:
std::string name;int age;};intmain(){
Student s("Navya",20);
s.display();return0;}
Output
Name: Navya, Age: 20
Why Use Constructor Initialization Lists?
- To avoid default initialization followed by reassignment, to save time and resources.
- It mandatory for certain types of const variables, reference members, and base class members.
- It keeps all initialization logic in one place, separate from the constructor body.
Special Cases
In the following, we will discuss few special cases for constructor initialization list −
Const or Reference Members
Const variables and reference members cannot be reassigned, so they must be initialized in an initialization list,
classConfig{public:Config(const std::string& product,constint& model):product(product),model(model){}private:const std::string product;constint& model;};
Base Class Initialization
When a derived class inherits from a base class, you can use an initialization list to call the base class constructor,
class Base { public: Base(int value) : baseValue(value) {} protected: int baseValue; }; class Derived : public Base { public: Derived(int value, int extra) : Base(value), extraValue(extra) {} private: int extraValue; };
Leave a Reply