CONSTRUCTOR IN C ++
Constructor:
- In c ++ Constructor is a special member function of class.
- Constructor is used for initializing the object of a class.
Rules for writing constructor:-
- Constructor will have same name as the class name.
- Constructor will get invoked automatically when a object of a class is created.
- Constructor will not return any value./Constructor will not have return type.
- Constructor should always declared in public area of the class.
- Main job of the constructor is to initialize the object of the class.
NOTE: Points to remember
(1)We can not create a virtual constructor.
(2)Even if we don’t define a constructor explicitly compiler will provide a default constructor implicitly.
(3)We can overload constructor.
- Types of constructor:-
- Parameterized constructor
- Default constructor
- Copy constructor
1.Parametrrized constructor-
The constructor in which it is possible to pass the arguments to a constructor which helps to initialize a object is called a parameterized constructor.
syntax- classname(parameters)
Example-
#include<iostream>
using namespace std;
class Box
{
int x, y;
public:
Box(int b1,int b2)
{
x=b1;
y=b2;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
Box myobj(30,25);
cout<< “ X: “<<myobj.getX()<<endl;
cout<<”Y: “ <<myobj.getY();
return 0;
}
Output:
X=30
Y=25
2.Deafault constructor-
A constructor which does not take ant arguments is knows as default constructor.
syntax- calssname()
Example-
#include <iostream>
using namespace std;
class box
{
int a ,b;
public:
box()
{
a=35;
b=24;
}
int geta()
{
return a;
}
int getb()
{
return b;
}
};
int main()
{
box b1;
cout<<”a: “<<b1.geta()<<endl;
cout<<”b: “<<b1.getb();
return 0;
}
Output-
a=35
b=24
3.Copy constructor-
A constructor which is used to copy the data of one constructor to another is known as copy constructor.
syntax-calssname (const classname & old_obj)
Example-
#include <iostream>
using namespace std;
class box
{
int x,y;
public:
box(int m,int n)// main constructor call
{
x=m;
y=n;
}
box(const box &b1)//copy constructor
{
x=b1.x;
y=b1.y;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
};
int main()
{
box b1(35,74);
box b2=b1;
cout<<”value of x in b1: “<<b1.getx()<<endl;
cout<<”value of y in b1: “<<b1.gety()<<endl;
cout<<”value of x in b2: “<<b2.getx()<<endl;
cout<<”value of y in b2: “<<b2.gety()<<endl;
return 0;
}
Output-
value of x in b1: 35
value of y in b1: 74
value of x in b2: 35
value of y in b2: 74