C++ Constructor Initializer List
A constructor initializer list in C++ is a way to directly initialize member variables when an object is created. It sets variable values before the constructor body runs. This helps make the program more efficient and is required for const variables, references, and base class objects.
Syntax
A constructor initializer list comes after the constructor’s name and parameter list. It starts with a colon (:) and is followed by a list of variables being initialized:
class ClassName {
private:
int x;
int y;
public:
ClassName(int a, int b) : x(a), y(b) {
// Constructor body (optional)
}
};
Examples
Using Constructor Initializer List
This example shows how to use a constructor initializer list to set values when an object is created:
#include <iostream>class Point {private:int x;int y;public:// Constructor using initializer listPoint(int a, int b) : x(a), y(b) {std::cout << "Point initialized with x = " << x << " and y = " << y << "\n";}};int main() {Point p1(3, 4); // Constructor is called with values 3 and 4return 0;}
The result of the above code is the following:
Point initialized with x = 3 and y = 4
Initializing Constant and Reference Members
If a class has const or reference variables, they must be initialized using a constructor initializer list since they cannot be assigned values later:
#include <iostream>class Example {private:const int value;int& ref;public:Example(int v, int& r) : value(v), ref(r) {std::cout << "Const value: " << value << " | Reference value: " << ref << "\n";}};int main() {int num = 10;Example ex(5, num);return 0;}
The result of the above code is the following:
Const value: 5 | Reference value: 10
Codebyte Example
This example demonstrates how a constructor initializer list can be used to initialize multiple members, including a base class and constant members:
Explanation
- The
Baseclass has a constructor that initializesbaseValueusing an initializer list. - The
Derivedclass inherits fromBaseand initializes its own members using an initializer list. - The
Derivedclass constructor first calls theBaseclass constructor and then initializesderivedValue(a const member) andnormalValue. - The initializer list ensures all members are set before the constructor body executes.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours