To know about constructor firstly have a look on object and class , concept of constructor is generated due to object so its better to go to this below link if you are not familiar with object and class of cpp
class and object in cpp
Now ,constructor is a function which give the memory existence of an object
1.Constructor is used to initialize the data member of an object .
2.It's allocate the memory for object .
3.Constructor has the same name as name of class.
4.Whenever a object is created ,constructor is called
5. Constructor doesn't return any value and it's get called whenever an object is created.
Ex-
#include<iostream>
using namespace std;
class Box
{
int length,width,height ;
public:
Box() // By default Constructor
{
}
int volume() ;
};
int Box ::volume()
{
cout <<"Enter the length height and width of box";
cin>>length>>width>>height ;
return length*width*height;
}
int main()
{
Box b;
//object created(constructor calling without parameter
cout<<"volume of the Box is :"<< b.volume();
return 0 ;
}
output :
Enter the length height and width of box
12 10 20
The volume of Box is :2400
int length,width,height ;
public:
Box() // By default Constructor
{
}
int volume() ;
};
int Box ::volume()
{
cout <<"Enter the length height and width of box";
cin>>length>>width>>height ;
return length*width*height;
}
int main()
{
Box b;
you can see here the constructor Box() ,with the same name of class but it's doing nothing. this is By Default constructor called by compiler
if we pass any value to this constructor that will be user defined constructor and benefit of user defined constructor is we can initialize the data member of object according to our need .
Next program will explain this concept .
#include<iostream>
using namespace std;
class Box
{
int length,width,height ;
public:
Box(int x,int y,int z)// user defined Constructor {
length=x;
width=y;
height=z;
}
int volume() ;
};
int Box ::volume()
{
return length*width*height;
}
int main()
{
Box b(10,20,12); // object created(constructor with parameter)
cout<<"volume of the Box is :"<< b.volume();
return 0 ;
}
OUTPUT
0 comments: