C/C++

C++ Constructors and types of Constructors with example

C++ Constructors:

A C++ constructor is a member function of a class that is called and executed automatically when an object of that class is created. The name of the constructor function is the same as the name f the class itself.

A constructor function may have arguments but it cannot return any value.



Example: how to create a c++ constructors in programming:

Output:

In the above program, the class “data” contains member function “data”. This member function is the c++ constructors function because the name of this function and the name of the class are the same. When the member function “data” is executed, it prints “programming digest” on the computer screen.

In the program, three objects (a,b, and c) of the class “data are created. Each time an object f the class “data” is created, the constructor is executed and the word “ programming digest” is printed on the computer screen. Since three objects are created, the word programming digest is printed three times.


Initializing data using C++ Constructors:

The constructor functions are normally used to initialize values in data members of a class when the program is executed. This type of initialization is called automatic initialization.

For example, if the member function has two arguments of int type, the specified values can be assigned to the data member of the class using a constructor as shown below:

Output:

In the above program when the object “a” of the class “sum” is created, the control shifts to the constructor function “sum”. The c++ constructor function assigns values to variables n and m and its also calculates their sum. Thus when data function is executed by the object a, the values assigned to the data members of the object by the constructor are printed.

Similarly when the object b is created, the c++ constructor function is automatically executed.


C++ constructors Overloading:

More than one c++ constructor function can be defined in one class when more than one c++ constructors function are defined, each c++ constructors is defined with a different set of parameters. Defining more than one constructor with different set of parameters is called c++ constructors overloading.

When a program that uses the c++ constructors overloading is compiled, c++ compiler checks the number of parameters, their order and data types and marks them differently. When an object of the class is created, the corresponding c++ constructors that matches the number of parameters of the object function is executed.

In the following example, two constructors functions are defined in class “sum”

Example how to use c++ constructors overloading in programming:

Output:

when the program is executed, the object x is created first and them the sum constructor function that has only two integer type parameters is executed.

Then the y object is created. It has three parameters of integer type so the c++ constructors function that has three arguments of integer type is executed.



Example how to use constructors overloading function in c++ Programming:

programm Explanation:

This C++ code defines a class named find with two constructors. The first constructor is a parameterized constructor that takes three integer arguments x, y, and z. It finds the maximum of these three numbers and stores it in the private member variable mx. Then, it prints a message to the console indicating the maximum number.

The second constructor is also a parameterized constructor that takes two integer arguments x and y. It finds the maximum of these two numbers and stores it in the private member variable mx. Then, it prints a message to the console indicating the maximum number.

In the main() function, two objects of the find class are created using the two constructors. The first object data is created with two integer arguments a and b, and the second object datas is created with three integer arguments c, b, and a.

When the first object data is created, the second constructor is called, which finds the maximum between a and b and prints the result. When the second object datas is created, the first constructor is called, which finds the maximum between c, b, and a and prints the result.

The output of the program will be:


Types of C++ Constructors:

Parameterized constructors

C++ Constructors that can take at least one argument are termed as parameterized C++ constructors. When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method. If we want to initialize fields of the class with your own values, then use a parameterized C++ constructor.


Default constructors

If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a default constructor into your code on your behalf. These c++ constructors is known as the default constructor. You would not find it in your source code (the java file) as it would be inserted into the code during compilation and exists in .class file. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. In Java, a “default constructor” refer to nullary c++ constructors that is automatically generated by the compiler if no constructors have been defined for the class or in the absence of any programmer-defined constructors (e.g. in Java, the default constructor implicitly calls the superclass’s nullary constructor, then executes an empty body). All fields are left at their initial value of 0 (integer types), 0.0 (floating-point types), false (boolean type), or null (reference types).

Example:

Programm Explanation:

This C++ code defines a class named Box with a default constructor. The class has three private member variables m_width, m_height, and m_length, and a public member function Volume which returns the volume of the box calculated by multiplying the three variables.

The default constructor is a constructor that takes no arguments. In this code, the default constructor is compiler-generated because the user did not define any constructor explicitly. The default constructor initializes the three member variables m_width, m_height, and m_length to their default values, which are 0 in this case.

In the main() function, an object box1 of the Box class is created using the default constructor. When box1 is created, the default constructor is called implicitly to initialize the member variables to their default values.

The program then calls the Volume member function of the box1 object, which calculates and returns the volume of the box by multiplying the three member variables. However, since the three member variables were initialized to 0 by the default constructor, the output of box1.Volume() will be 0.

The output of the program will be:



Copy constructors in c++:

In C++, a copy constructor is a special constructor that is used to create a new object as a copy of an existing object of the same class. It is called when an object is initialized with another object of the same class, either by direct initialization or by passing an object as a function argument by value.

A copy constructor takes a reference to an object of the same class as a parameter and creates a new object that is a copy of the referenced object. The copy constructor is typically defined with the following signature:

where ClassName is the name of the class, and other is the reference to the object that is being copied.

Implicit copy constructor in c++:

In C++, an implicit copy constructor is a constructor that is generated by the compiler automatically when a class does not have any user-defined copy constructor.

The implicit copy constructor is responsible for creating a copy of an object when an object is passed by value, returned from a function, or assigned to another object using the assignment operator.

The implicit copy constructor creates a new object that is a copy of the original object, member-wise. It copies all non-static member variables of the original object into the new object.

For example, consider the following code:

In the above code, p1 is an object of the Person class. When p1 is copied to p2 using the assignment operator, the implicit copy constructor is called. It copies the value of the age member variable from p1 to p2. Thus, the output of the above code will be 25.

It is important to note that the implicit copy constructor only performs a shallow copy of the object’s member variables. If a class contains pointers to dynamically allocated memory, the implicit copy constructor will copy the pointer, but not the memory it points to. In this case, a user-defined copy constructor should be provided to ensure that the memory is properly copied.


User-defined copy constructor in c++:

In C++, a user-defined copy constructor is a constructor that is defined by the programmer to create a copy of an object of a class. It is used to ensure that a deep copy of the object is made, especially when the object contains dynamically allocated memory.

To define a user-defined copy constructor in C++, the following steps can be followed:

Declare a copy constructor in the class definition. The copy constructor should take a reference to an object of the same class as a parameter.

Define the copy constructor outside the class definition. The copy constructor should make a deep copy of the object by copying all member variables, including any dynamically allocated memory.

Here’s an example program that shows the use of a user-defined copy constructor:

In this program, the MyClass class contains a pointer to dynamically allocated memory. The user-defined copy constructor makes a deep copy of the object by allocating new memory and copying the value of the pointer.

When obj1 is copied to obj2, the user-defined copy constructor is called, and a deep copy of obj1 is made. The program then calls the destructor of obj1 to delete its memory. However, the memory of obj2 is not affected, as it was copied and allocated separately.

The output of the above program will be:


Conversion constructors in C++

In C++, a conversion constructor is a special type of constructor that is used to convert one data type to another. It allows a class to be used in contexts where another type is expected, by defining how objects of the class can be constructed from other types.

To define a conversion constructor in C++, the following steps can be followed:

Declare a constructor with a single parameter of a different type from the class.

Define the constructor outside the class definition.

Here’s an example program that shows the use of a conversion constructor:

In this program, the MyClass class has a conversion constructor that takes an integer value x. The constructor initializes the memberVar variable of the class with the value of x multiplied by 2.

When the statement MyClass obj = 5; is executed, the conversion constructor is called automatically to convert the integer value 5 to an object of type MyClass. The resulting object has its memberVar variable initialized with the value 10.

The output of the above program will be:



Move constructor in C++

In C++, a move constructor is a special member function of a class that enables the transfer of ownership of an object’s resources, such as memory buffers, from one object to another. It is typically used to optimize the performance of certain operations, such as returning a large object from a function or resizing a container.

A move constructor is defined with the following syntax:

The move constructor takes a single argument, which is an rvalue reference to another object of the same class. The rvalue reference indicates that the object being passed in can be safely modified or moved from, since it is not being used elsewhere.

Here’s an example program that shows the use of a move constructor:

In this example, we define a MyArray class that represents a dynamically allocated array of integers. The class has a move constructor that takes an rvalue reference to another MyArray object. The move constructor simply swaps the data_ and size_ members with the other object, and sets the other object’s members to null or 0.

In the main() function, we create two MyArray objects, arr1, and arr2. arr1 is initialized with a size of 5, and its elements are populated with the values 1 through 5. arr2 is constructed by moving arr1 using the std::move() function.

After the move, arr1 is in an unspecified state, as its members have been modified by the move constructor. Attempting to use arr1 after the move would result in undefined behavior, since its memory has been moved to arr2.

Finally, we output the size and value of an element of arr2, to demonstrate that arr2 has been properly initialized with the data from arr1.

The output of the above program will be:

Related Article:

Destructor in C++ with example

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button