Types of Constructor in Object Oriented Programming.
Types of constructor;
1. Default constructor
2. Parameterized constructor
3. Copy Constructor
1. Default constructor: A default constructor is the type of constructor with the same class name and it initialize itself when object of that class created.
Example:
#include <iostream>
using namespace std;
class circle
{
float area,radius;
public:
circle()
{
cout<<"Enter Radius of circle ";
cin>>radius;
}
void computeArea()
{
area=3.14*radius*radius;
}
void displayArea()
{
cout<<"Area of circle ="<<area;
}
};
int main()
{
circle circleObj;
circleObj.computeArea();
circleObj.displayArea();
return 0;
}
Output:
2. Parameterized constructor: A parameterized constructor is the type of constructor which take parameter as an argument.
Example:
#include <iostream>
using namespace std;
class circle
{
float area,radius;
public:
circle(int rad)
{
radius=rad;
}
void computeArea()
{
area=3.14*radius*radius;
}
void displayArea()
{
cout<<"Area of circle ="<<area;
}
};
int main()
{
circle circleObj(4);
circleObj.computeArea();
circleObj.displayArea();
return 0;
}
Output:
3. Copy Constructor: A copy constructor is the type of constructor which take object of class as a parameter.
Example:
#include <iostream>
using namespace std;
class point {
int num1,num2;
public:
point(int no1,int no2)
{
num1=no1;
num2=no2;
}
point(point &obj)
{
num1=obj.num1;
num2=obj.num2;
}
int getnum2()
{
return num2;
}
int getnum1()
{
return num1;
}
};
int main()
{
point pointObj1(10,12);
point pointObj2=pointObj1;
cout<<pointObj2.getnum1()<<"\n";
cout<<pointObj2.getnum2();
return 0;
}
Output:
Comments
Post a Comment