![]() |
VOOZH | about |
Constructors are special methods that are automatically called whenever an object of a class is created. A constructor is different from normal functions in following ways:
Constructor called
Explanation: In the above program, we have defined a constructor for class A. In the main function, when we create an object of that class, this constructor is called, which prints "Constructor called".
Constructors can be classified based on the situations they are being used in. There are 4 types of constructors in C++:
A default constructor is automatically created by the compiler if no constructor is defined. It takes no arguments and initializes members with default values, and it is not generated if the programmer defines any constructor.
Explanation: The class A does not contain any explicitly defined constructor, so its object is created without passing any parameters. In this case, the compiler automatically provides and uses the default constructor.
A parameterized constructor lets us pass arguments to initialize an object's members. It is created by adding parameters to the constructor and using them to set the values of the data members.
10
Explanation: The parameterized constructor is called when we create object a with integer argument 10 . As defined, it initializes the member variable val with the value 10.
Note: If a parameterized constructor is defined, the non-parameterized constructor should also be defined as compiler does not create the default constructor.
A copy constructor is a member function that initializes an object using another object of the same class. Copy constructor takes a reference to an object of the same class as an argument.
20
Explanation: The copy constructor is used to create a new object a2 as a copy of the object a1. It is called automatically when the object of class A is passed as constructor argument.
Just like the default constructor, the C++ compiler also provides an implicit copy constructor if the explicit copy constructor definition is not present.
Note: If no copy or move constructor is defined, the compiler automatically creates an implicit copy constructor, unlike the default constructor which is removed when any constructor is defined.
A move constructor in C++ transfers resources from one object to another instead of copying them. It uses move semantics to avoid unnecessary copies and improve performance, especially with temporary objects.
Move constructor called! 4
Explanation: In the above program, MyClass uses a constructor with an rvalue reference (int&&) to move a value into its member using std::move. When an object is created with std::move, the move constructor transfers ownership of resources instead of copying them. If you donβt define one, the compiler automatically generates a move constructor (just like it does for copy constructors).