I am reading the tutorial here.I read the constructor part but I didn't get alot.
Can anyone please tell me which line in this program shows the constructor and exlain constructor in easy words.I will be really thankful.
#include <iostream>
usingnamespace std;
class CRectangle {
int width, height;
public:
CRectangle (int,int); // constructor declaration, constructors take the same name as the class
int area () {return (width*height);}
};
CRectangle::CRectangle (int a, int b) { // constructor implementation, setting the values of with and height (which otherwise would be whatever happened to be in the memory)
width = a;
height = b;
}
int main () {
CRectangle rect (3,4); // using the constructor
CRectangle rectb (5,6); // using the constructor on another object of the same clasee
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
Constructors are similar to member functions, but are only called when a new object of that class is made (constructed).