











Types of Constructors in C++
Constructors in C++
Constructors
are special class functions which performs initialization of every object.- Whenever an object is created the Compiler calls the Constructor.
- Constructors initialize values to object members after storage is allocated to the object.
Syntax
class C
{
public:
int a;
// constructor
C()
{
// object initialization
}
};


Points to Remember
- The name of constructor will be same as the name of the class.
- Constructors will never have a return type.
There are 3 types of constructors
- Default Constructor
- Parameterized Constructor
- Copy Constructor
Default Constructor
- Default constructor is the constructor which doesn’t take any argument.
- It has no parameter.
- As soon as the object is created the constructor is called which initializes its data members.
- A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly
Syntax
class_name()
{
// constructor Definition
}
Example:
class Square
{
public:
int side;
Square()
{
side = 5;
}
};
int main()
{
Square s;
cout << s.side;
}
Output
10
Parameterized Constructors
- These are the constructors with parameters.
- Using this constructor we can provide different values to data members of different objects, by passing the appropriate values as argument.
Syntax
class_name(parameter1, parameter2, ...)
{
// constructor Definition
}
Example
class Square
{
public:
int side;
Square(int a)
{
side=a;
}
};
int main()
{
Square s1(5);
Square s2(10);
cout << s1.side;
cout << s2.side;
}
Output
5
10
- In the above example, we have initialized 2 objects with user defined values.
- We can have any number of parameters in a constructor.
Copy Constructor
- Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type.
- It is usually of the form C (C&), where C is the class name.
- A default Copy Constructor is provided to all the classes by compiler.
Syntax
Classname(const classname & objectname)
{
. . . .
}


Example
#include<iostream>
using namespace std;
class Sample_copy_constructor
{
private:
int a, b; //data members
public:
Sample_copy_constructor(int a1, int b1)
{
a = a1;
b = b1;
}
/* Copy constructor */
Sample_copy_constructor (const Sample_copy_constructor &sample)
{
a = sample.a;
b = sample.b;
}
void display()
{
cout<<a<<" "<<b<<endl;
}
};
/* main function */
int main()
{
Sample_copy_constructor obj1(10, 20); // Normal constructor
Sample_copy_constructor obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Output
Normal constructor : 10 15
Copy constructor : 10 15