Constructor
·
The member functions which provide the initial
values to the variables during the creation of an object are called constructor.
·
It is a member function having same name as it’s
class and which is used to initialize the objects of that class type with a legal
initial value.
·
Constructor is automatically called when object is
created.
Types of Constructor
1. Default Constructor.
2. Parameterized Constructor.
3. Copy Constructor.
1. Default
Constructor-: A constructor that accepts no parameters is known as
default constructor. If no constructor is defined then the compiler supplies a
default constructor.
Circle :: Circle()
{
radius = 0;
}
Parameterized Constructor -:
A constructor that receives arguments/parameters, is called parameterized
constructor.
Circle :: Circle(double r)
{
radius = r;
}
For Example:
/*Programs Calculate Prime Number Using Constructor*/
#include<iostream.h>
#include<conio.h>
class prime
{
int a,k,i;
public:
prime(int x)
{
a=x;
}
void calculate()
{
k=1;
{
for(i=2;i<=a/2;i++)
if(a%i==0)
{
k=0;
break;
}
else
{
k=1;
} } }
void show()
{
if(k==1)
cout<< “\n\tA is prime Number. ";
else
cout<<"\n\tA is Not prime.";
}
};
void main()
{
clrscr();
int a;
cout<<"\n\tEnter the Number:";
cin>>a;
prime obj(a);
obj.calculate();
obj.show();
getch();
}
Expected Output:
Enter the number: 7
Given number is Prime Number
Copy Constructor-: A
constructor that initializes an object using values of another object passed to
it as parameter, is called copy constructor. It creates the copy of the passed
object.
Circle :: Circle(Circle &t)
{
radius = t.radius;
}
There can be multiple constructors of the same class,
provided they have different signatures.
Advantages of Constructor:
·
Constructor
function is used to initialize member variables to pre-defined
·
values
as soon as an object of a class is declared.
·
Constructor
function gets invoked when an object of a class is constructed
·
(declared).
·
So
basically Constructor is used to initialize the objects (at the time of
creation), and they are automatically invoked.
·
This
saves us from the garbage values assigned to data members; during initializing.