constructor questions

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

class CRectangle {
    int width, height;
  public:
    CRectangle (int,int);
    int area () {return (width*height);}
};

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

int main () {
  CRectangle rect (3,4);
  CRectangle rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace 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).
Last edited on
Topic archived. No new replies allowed.