C++ class, constructor
Constructors are special member functions of a class that initialize objects. There are several types of constructors, including default constructors, parameterized constructors, converting constructors, copy constructors, and move constructors.
- Default (zero-parameter) constructor: no arguments
- Parameterized constructor: accepting parameters
- Converting constructor: any non-explicit parameterized constructor (since C++11)
- Copy constructor of class T: T([const] [volatile] T&). Used to create a new object as a copy of an existing object. Called when:
- initialization: T a = b; or T a(b);, where b is of type T;
- function argument passing: f(a);, where a is of type T and f is void f(T t);
- Move constructor of class T: T([const] [volatile] T&&). Used to transfer resources from a temporary or moved object to a new object. It can efficiently handles resources without deep copying. Called when:
- initialization: T a = std::move(b); or T a(std::move(b));, where b is of type T;
- function argument passing: f(std::move(a));, where a is of type T and f is f(T t);
Code Example
Explanation
Default Constructor:
MyClass() {
cout << "Default (zero-parameter) constructor called via MyClass newObj" << endl;
x = 0;
}
- Initializes objects with no arguments.
- Called when an object is created without passing any parameters (e.g., MyClass m1).
Parameterized Constructor:
explicit MyClass(int x) {
cout << "Parameterized constructor called via: MyClass newObj(x)" << endl;
this->x = x;
}
- Initializes objects with provided arguments.
- Called when an object is created with specific parameters (e.g., MyClass m2(2)).
Converting Constructor:
MyClass(double x) {
cout << "Converting constructor called via: MyClass newObj = x;" << endl;
this->x = (int)x;
}
- Non-explicit parameterized constructor used for type conversion.
- Called when an object is initialized with a value of a different type (e.g., MyClass m3 = 3.14).
Copy Constructor
MyClass(const MyClass& m) {
cout << "Copy constructor called via: MyClass newObj = m, MyClass newObj(m), or MyFunc(m)" << endl;
this->x = m.x;
}
- Initializes objects by copying from another object.
- Called in scenarios such as object initialization (e.g., MyClass m4_1 = m1), function argument passing (e.g., myFunc(m1)).
Move Constructor:
MyClass(MyClass&& m) {
cout << "Move constructor called via: MyClass newObj = move(m), or MyFunc(move(m));" << endl;
this->x = m.x;
}
- Initializes objects by transferring resources from another object.
- Called in scenarios such as object initialization with std::move (e.g., MyClass m5 = move(m1)), function argument passing with std::move (e.g., myFunc(move(m5))).
Conclusion
Understanding the different types of constructors in C++ is essential for proper object initialization and resource management. Each type of constructor serves a specific purpose, ensuring that objects are created and managed efficiently.