What are the various types of constructors used in object oriented programming? Explain with an example.
1) Default Constructor in C++
Sample Code:
#include<iostream>
using namespace std;
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
construct c;
int sum = c.a + c.b;
cout << "a : " << c.a << endl;
cout << "b : " << c.b << endl;
cout << "sum : " << sum << endl;
return 0;
}
2) Parameterized Constructor in C++
Sample Code:
#include<iostream>
using namespace std;
class PrepInsta {
private:
int a, b;
public:
PrepInsta(int a1, int b1)
{
a = a1;
b = b1;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
};
int main()
{
PrepInsta obj1(10, 15);
cout << "a = " << obj1.getA() << ", b = " << obj1.getB();
return 0;
}
3) Copy Constructor in C++
Sample code:
#include<iostream>
using namespace std;
class PrepInsta
{
private:
int x, y;
public:
PrepInsta()
{ // empty default constuctor
}
PrepInsta(int x1, int y1)
{
x = x1;
y = y1;
cout << "Parameterized constructor called here" << endl;
}
// User defined Copy constructor
PrepInsta(const PrepInsta &p2)
{
x = p2.x;
y = p2.y;
cout << "Copy constructor called here" << endl;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Trying to call parameterized constructor here
PrepInsta p1(10, 15);
// Trying to call copy constructor here
PrepInsta p2 = p1;
// Trying to call Copy constructor here (Another way of doing so)
PrepInsta p3(p1);
PrepInsta p4;
// Here there is no copy constructor called only assignment operator happens
p4 = p1;
cout << "\nFor p4 no copy constructor called only assignment operation happens\n" << endl;
// displaying values for both constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
cout << "\np3.x = " << p3.getX() << ", p3.y = " << p3.getY();
cout << "\np4.x = " << p4.getX() << ", p4.y = " << p4.getY();
return 0;
}
Comments
Leave a comment