C++ Programming

C++ Constructors and its types with example codes

C++ Constructors:

C++ Constructors– A 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.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Example: how to create C++ constructors in programming:

#include <iostream>

using namespace std;
class data
{
    public:
    data()
    {
        cout<<" Electronic Clinic"<<endl;
    }
   
};
int main()
{
    data a, b,c;

    return 0;
}
Output:
Electronic Clinic
Electronic Clinic
Electronic Clinic

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 “Electronic Clinic” 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 function is 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:

#include <iostream>

using namespace std;
class sum
{
   private:
   int n, m, s;
   public:
   sum(int x, int y)
   {
       n=x;
       m=y;
       s=n+m;
   }
   data ()
   {
       cout<<"Sum of "<<n<<"and"<<m<<"is"<<s<<endl;
   }
};
int main()
{
    sum a(17,40);
    sum b(6,9);
    a.data();
    b.data();

    return 0;
}
Output:
Sum of 17 and 40 is 57
Sum of 6 and 9 is 15

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 it also calculates their sum. Thus when the data function is executed by the object, 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++ constructor function is defined, each C++ constructor is defined with a different set of parameters. Defining more than one constructor with a different set of parameters is called C++ constructors overloading.

When a program that uses the C++ constructors overloading is compiled, the 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 match the number of parameters of the objective function is executed.

In the following example, two constructor function are defined in class “sum”


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

#include <iostream>

using namespace std;
class sum
{
   
   public:
   sum(int l, int m, int n)
   {
       cout<<"sum of 3 integers is= "<<(l+m+n)<<endl;

   }
   sum(int l, int m)
   {
       cout<<"sum of 2 integers is"<<(l+m)<<endl;
   }
};
int main()
{
    sum x(4,5), y(2,3,5);

    return 0;
}
Output:
sum of 2 integers is9
sum of 3 integers is= 10

when the program is executed, the object x is created first and then 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:

#include <iostream>

using namespace std;
class find
{
   private:
   int mx;
   public:
   find(int x, int y, int z)
   {
       if(x>y)
       if (x>z)
       mx=x;
       else
       mx=z;
       else if (y > z)
       mx=y;
       else
       mx=z;
       cout<<"Maximum between three number is : "<<mx<<endl;
       
   }
   find(int x, int y)
   {
       if(x>y)
       mx=x;
       else
       mx=y;
       cout<<"maximum between two number is : "<<mx<<endl;
       
   }
  
};
 int main()
{
   int a=30, b=49, c=90;
   find data(a,b);
   find datas(c,b,a);

    return 0;
}


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.

class Example {
 public:
  Example();
  Example(int a, int b);  // Parameterized constructor.

 private:
  int x_;
  int y_;
};

Example::Example() = default;

Example::Example(int x, int y) : x_(x), y_(y) {}
Example e = Example(0, 50);  // Explicit call.
Example e2(0, 50);  // Implicit call.

Default constructors

If the programmer does not supply a constructor for an instantiable class, the Java compiler inserts a default constructor into your code on your behalf. This C++ constructor 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 the .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” refers to a nullary C++ constructor 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).

#include <iostream>

class Student {
 public:
  Student(int a = 0, int b = 0);  // Default constructor.

  int a;
  int b;
};

Example :

#include <iostream>
using namespace std;

class Box {
public:
    int Volume() {return m_width * m_height * m_length;}
private:
    int m_width { 0 };
    int m_height { 0 };
    int m_length { 0 };
};

int main() {
    Box box1; // Invoke compiler-generated constructor
    cout << "box1.Volume: " << box1.Volume() << endl; // Outputs 0
}

If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example. Without those initializes, the members would be uninitialized and the Volume() call would produce a garbage value. In general, it is good practice to initialize members in this way even when not relying on an implicit default constructor.


Copy constructors

A copy constructor initializes an object by copying the member values from an object of the same type. If your class members are all simple types such as scalar values, the compiler-generated copy constructor is sufficient and you do not need to define your own. If your class requires more complex initialization, then you need to implement a custom copy constructor. For example, if a class member is a pointer then you need to define a copy constructor to allocate new memory and copy the values from the other’s pointed-to object. The compiler-generated copy constructor simply copies the pointer, so that the new pointer still points to the other’s memory location.

Implicit copy constructor

#include <iostream>

class Person {
 public:
  explicit Person(int age) : age(age) {}

  int age;
};

int main() {
  Person timmy(10);
  Person sally(15);

  Person timmy_clone = timmy;
  std::cout << timmy.age << " " << sally.age << " " << timmy_clone.age
            << std::endl;
  timmy.age = 23;
  std::cout << timmy.age << " " << sally.age << " " << timmy_clone.age
            << std::endl;
}

Output
10 15 10
23 15 10



User-defined copy constructor

Now, consider a very simple dynamic array class like the following:

#include <iostream>

class Array {
 public:
  explicit Array(int size) : size(size), data(new int[size]) {}

  ~Array() {
    if (data != nullptr) {
      delete[] data;
    }
  }

  int size;
  int* data;
};

int main() {
  Array first(20);
  first.data[0] = 25;

  {
    Array copy = first;
    std::cout << first.data[0] << " " << copy.data[0] << std::endl;
  }  // (1)

  first.data[0] = 10;  // (2)
}

Output
25 25
Segmentation fault

Conversion C++ constructors

Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These C++ constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.


Move C++ constructors

In C++, move constructors take a value refers to an object of the class, and are used to implement ownership transfer of the parameter object’s resources.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button