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.

  1. Default (zero-parameter) constructor: no arguments
  2. Parameterized constructor: accepting parameters
  3. Converting constructor: any non-explicit parameterized constructor (since C++11)
  4. 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);
  5. 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);
because of Return Value Optimization (RVO), most compilers don't invoke copy/move constructor when returning an object such as T f() {return T a;}.

Code Example


Explanation

Default Constructor:

MyClass() {
  cout << "Default (zero-parameter) constructor called via MyClass newObj" << endl;
  x = 0;
}

Parameterized Constructor:

explicit MyClass(int x) {
  cout << "Parameterized constructor called via: MyClass newObj(x)" << endl;
  this->x = x;
}

Converting Constructor:

MyClass(double x) {
  cout << "Converting constructor called via: MyClass newObj = x;" << endl;
  this->x = (int)x;
}

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;
}

Move Constructor:

MyClass(MyClass&& m) {
  cout << "Move constructor called via: MyClass newObj = move(m), or MyFunc(move(m));" << endl;
  this->x = m.x;
}

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.