Constructors are special member functions in a class that are automatically called when an object of the class is created.
Their primary purpose is to initialize the object's data members and allocate any required resources.
Constructors play a crucial role in setting up the initial state of objects and ensuring that they are ready for use.
- Constructors are called automatically when you create an object. They set up the object before you use it.
- Constructors initialize the object's data members to meaningful values.
- Constructors have same name as the name of the class.
- Constructors don't have a return type.
- You can have multiple constructors with different parameter lists for versatility.
- If you don't define any constructors, a default constructor (with no parameters) is provided.
- Default Constructor
- Non Parametrized Constructor
- Parametrized Constructor
- Copy Constructor
It initializes the object's data members to their default values. If you don't define any constructors, the compiler automatically generates a default constructor.
#include<iostream>
using namespace std;
class Solution
{
int n;
public:
Solution()
{
n=10;
}
void getData()
{
cout<<n<<endl;
}
};
int main()
{
Solution obj;
obj.getData();
}
A parameterized constructor accepts parameters, allowing you to initialize data members with specific values during object creation.
It provides flexibility in object initialization.
#include<iostream>
using namespace std;
class Solution
{
int n;
public:
Solution(int n)
{
this->n = n;
}
void getData()
{
cout<<n<<endl;
}
};
int main()
{
Solution obj(10);
obj.getData();
}
A copy constructor creates a new object by copying the values of another object.
It takes an object of the same class as a parameter and initializes the new object with the same values. This is used when you want to create a duplicate of an existing object.
#include<iostream>
using namespace std;
class Solution
{
int num, num2;
public:
Solution(int var)
{
num = var;
}
Solution(Solution &obj2)
{
num2 = obj2.num;
}
void getData()
{
cout<<num<<endl;
}
void getData2()
{
cout<<num2<<endl;
}
~Solution()
{
}
};
int main()
{
int var;
cout<<"Enter var";
cin>>var;
Solution obj(var);
obj.getData();
Solution obj2 = obj;
obj2.getData2();
}
MSTAKE
#include<iostream>
using namespace std;
class Solution
{
int n1, n2;
public:
Solution(int n)
{
n1 = n;
}
void getData()
{
cout<<n1<<endl;
}
Solution(const Solution &obj2Ref)
{
n2 = obj2Ref.n1;
}
void getDataforCopy()
{
cout<<n2<<endl;
}
};
int main()
{
Solution obj(10);
obj.getData();
Solution obj2 = obj;
obj.getDataforCopy();
}