Wednesday, March 04, 2009

What is constructor?

Constructor is function specialized for class.
When a class is built, a default constructor is built for it.

class CRec {
int width, height; //private data member
public:
CRect(int,int); //declaring ctor
int area() { return(width*height)};
};

CRec::CRec(int a, int b) // defining ctor
{
width = a;
height = b;
}

int main() {
CRec rect(3,4); //create object rect
CRec retb(5,6);

//use the objects created and call the member functions
cout<< "rect area;" << rect.area() <cout<<"rect area:"<return 0;
}

the objects of this class is created through int main(), instead of stating at the end of class.
constructors cannot be called explicitly as if they regular member functions. They are only excuted when a new object of that class is created.

and Constructor can be overloaded same as function but the compiler will call the one whose parameres matches the arguments used in the function called for example:

//declaration
class CRec{
int width, height;
public:
CRec();//default ctor
CRec(int, int);//ctor(overloaded)
int area (void){return(width*height);}; //inline function
};

//implementation
CRec::CRec(){
width = 5;
height=5;
}

CRec::CRec(int a, int b){
width = a;
height=b;
}

int main(){
//create objects
CRec rect(3,4);
CRec rectb; //default ctor called and () is not required or allowed.

//use objects
cout <<"rect area:" <cout<<"rectb area:"<return 0;
}

No comments:

Related Posts Plugin for WordPress, Blogger...