Types Of Constructor In C++
- Default
constructor
- Parameterized
constructor
- Copy constructor
1.
Default Constructor
A constructor that doesn’t have parameters. It is invoked
automatically and can carry default values. If we do not define constructor it
will still define an empty constructor.
Synatx:
class BCA
{
int a,b;
public:
class name()//default constructor
{
---
---
}
};
Program:
#include<iostream.h>
#include<conio.h>
class BCA
{
private:
int
a,b;
public:
BCA()
{
cout<<”default
constructor create”;
}
void
display()
{
cin>>a>>b;
cout<<”a=”<<a;
cout<<”b=”<<b;
}
};
void
main()
{
BCA
a1;
a1.display();
getch();
}
Output:
Default
constructor create a=0 b=775
2.
Parameterize Constructor
When we can pass values to
constructor it is called parameterized constructor. Passing values to the
constructors are same as with functions. It is used to initialize variables in
a class.
Synatx:
class BCA
{
int a,b;
public:
class name(argument)//parameterize constructor
{
---
---
}
};
Program:
#include<iostream.h>
#include<conio.h>
class BCA
{
private:
int
a,b;
public:
BCA(int
x, int y)
{
cout<<”parameterize
constructor create”;
a=x;
b=y;
}
void
display()
};
void
BCA::display()
{
cout<<”a=”<<a;
cout<<”b=”<<b;
}
void
main()
{
BCA
a1(100,200);
a1.display();
getch();
}
Output:
Parameterize constructor create a=100 b=200
3.
Copy Constructor
A copy constructor is used to copy the variable
of one object into another object.
Synatx:
class BCA
{
int a,b;
public:
class name(class name &object name)//copy constructor
{
---
---
}
};
Program:
#include<iostream.h>
#include<conio.h>
class BCA
{
private:
int
a,b;
public:
BCA()//default
constructor
{
cout<<”create
a constructor”;
a=0;
b=0;
}
BCA(int
x, int y)//parameterize constructor
{
a=x;
b=y;
}
BCA(BCA
&p)//copy constructor
{
a=p.a;
b=p.b;
}
void
display()
{
cout<<a;
cout<<b;
}
};
void
main()
{
BCA
a1;
BCA
a2(10,20);
BCA
a3(a2);
a1.display();
a2.display();
a3.display();
getch();
}
Output:
Create constructor 0010201020
No comments:
Post a Comment