C++ Constructor Initialization: A Complete Guide
In C++, the constructor initialization list is a way to initialize an object’s member variables. Using the constructor initialization list allows for directly assigning values to member variables when the object is created, without the need to individually initialize each member variable within the constructor body.
Here is an example of using a constructor initializer list:
#include <iostream>
class MyClass {
public:
MyClass(int a, int b) : x(a), y(b) {
// 构造函数体内不需要再对 x 和 y 进行赋值
}
void print() {
std::cout << "x = " << x << ", y = " << y << std::endl;
}
private:
int x;
int y;
};
int main() {
MyClass obj(10, 20);
obj.print();
return 0;
}
In the example above, the x(a) and y(b) in the constructor initialization list MyClass(int a, int b) : x(a), y(b) initialize the member variables x and y, where a and b are parameters of the constructor. By using the constructor initialization list, we can directly assign values to member variables, making the code more concise and efficient.