How do I use member initializer lists in C++?

In C++, member initializer lists are used to initialize class members before the constructor's body executes. This feature is particularly useful for initializing constants, references, or members that don't have a default constructor.

Example of Member Initializer Lists

class Rectangle { private: int width, height; public: // Constructor using member initializer list Rectangle(int w, int h) : width(w), height(h) { // Constructor body can be empty or can perform other tasks } int area() { return width * height; } }; int main() { Rectangle rect(10, 5); std::cout << "Area: " << rect.area() << std::endl; return 0; }

Member Initializer Lists C++ Constructors Class Members Object Initialization