C++ - Constructor Initializer

This post will go through the shorthand for initializing c++ class member variables.

Constructor Member Initializer List allows us to initialize a class’ data members in the constructor. There 2 main ways for us to initialize data members in a constructor.

 

Traditional way

class Person
{
public:
    string pName;
    int age;
    Person() {
        pName = "Alice";
        age = 0;
    }

    Person(string name) {
        pName = name;
        age = 0;
    }

    Person(string name, int val) {
        pName = name;
        age = val;
    }
};

int main() {
    Person *s1 = new Person();
    cout << "pName: " << s1->pName << ", age: " << s1->age << endl;
    Person *s2 = new Person("Bob");
    cout << "pName: " << s2->pName << ", age: " << s2->age << endl;
    Person *s3 = new Person("Charlie", 10);
    cout << "pName: " << s3->pName << ", age: " << s3->age << endl;
}

 

Output:

p1: Alice, age: 0
p2: Bob, age: 0
p3: Charlie, age: 10

In CPP, there is an alternative way to do this: member initialization list.

 

Member Initialization List

This can be think of as a shorthand of the traditional way to initialize. It makes our code look cleaner especially when we have a lot of data members.

class Person
{
public:
    string pName;
    int age;
    Person() : pName("Alice"), age(0) {}
    Person(string name) : pName(name), age(0) {}
    Person(string name, int val) : pName(name), age(val) {}
};

  Output:

p1: Alice, age: 0
p2: Bob, age: 0
p3: Charlie, age: 10

As we can see from above, we can achieve the same result as using the traditional way but the code is short and concise while the readability is kept. We can also choose to use default arguments to further shorten the code:

class Person
{
public:
    string pName;
    int age;
    Person(string name = "Alice", int val = 0) : pName(name), age(val) {}
};

 

Examples

Since Class and Structs in CPP are very similar to each other, Structs can also take advantage of this feature. Below is an example of constructor initializer list from Leetcode

// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};