C++ Constructors

WHAT ARE CONSTRUCTORS?

  • The constructor is a member function of a class which initialized the objects of a class. The constructor will be called automatically when an object is created.
  • The constructor has the same name as of the class and it does not have any return type.

HOW THE CONSTRUCTORS ARE DIFFERENT FROM A MEMBER FUNCTION?

The constructors are different from the member function in such ways like:

  • Constructor can be called automatically when an object is created.
  • The constructor name is same as of the class.
  • It does not have the return type.
  • If the constructor is not specified than the compiler will generate a default constructor.

TYPES OF CONSTRUCTORS

There are two types of constructors:

  • Default Constructor
  • Parameterized Constructor

DEFAULT CONSTRUCTOR:

The default constructor is the constructor which does not accept any argument. It does not have any parameters.

LET US UNDERSTAND THIS THROUGH AN EXAMPLE:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
 
using namespace std;
 
  class test_construct {
 
public:
 
    int x, y;
 
    // Default Constructor
 
    test_construct()
 
    {
 
        x = 20;
 
        y = 100;
 
    }
 
};
 
int main()
 
{
 
    // Default constructor called automatically
 
    // when the object is created
 
    test_construct t;
 
    cout << “x: “ << t.x << endl
 
         << “y: “ << t.y;
 
    return 1;
 
}

Output 

X is : 20

Y is : 100

PARAMETERIZED CONSTRUCTOR:

  • In the parameterized constructor we can pass the arguments to the constructor. The arguments will help to initialize an object when it is created.
  • Define the constructor’s body then the parameters are used to initialize the object.

LET US HAVE A LOOK AT THE EXAMPLE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
 
using namespace std;
 
class Parameterized {
 
private:
 
    int a, b;
 
public:
 
    // Parameterized Constructor
 
    Parameterized(int a1, int b1)
 
    {
 
        a = a1;
 
        b = b1;
 
    }
 
    int getA()
 
    {
 
        return a;
 
    }
 
    int getB()
 
    {
 
        return b;
 
    }
 
};
 
int main()
 
{
 
    // Constructor called
 
    Parameterized p1(20, 35);
 
    // Access values assigned by constructor
 
    cout << “p1.a = “ << p1.getA() << “, p1.b = “ << p1.getB();
 
    return 0;
 
}

Output : 

p1.a = 20

p1.b =35

WHAT ARE THE USES OF PARAMETERIZED CONSTRUCTOR?

  • They are used to initialize the various data elements of different objects with different values when they are created.
  • This constructor is used to overload constructors.