Constructors

When you have a class with one constructor with parameters such as:
1
2
3
4
5
6
7
8
9
10
11
class CRectangle {
    int width, height;
  public:
    CRectangle (int,int);
    int area () {return (width*height);}
};

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

You can create a CRectangle object with:
 
CRectangle rect (3,4);


Now if you have a class with two types of constructors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CRectangle {
    int width, height;
  public:
    CRectangle ();
    CRectangle (int,int);
    int area (void) {return (width*height);}
};

CRectangle::CRectangle () {
  width = 5;
  height = 5;
}

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

Can you create an CRectangle object using either constructors? If yes, why when creating a CRectangle object without parameters, why do we not include the () besides the fact that it has no parameters?
Yes, you can create the object using either constructor and it will work just fine. And I don't know why you don't have the () when you have no parameters in the constructor. Im guessing it is to explicitly show you are calling the constructor with no parameter or something.

You can even do this with regular functions as well, it is called Function overloading. The two functions can have the same name, and take in different parameters, and the compiler will know which function to call depending on what parameters you pass in. In this example though, you do need the () even when you have no parameters for the function.
Last edited on
Yes, you can create a CRectangle object using either constructor.

When you call the constructor without parameters (this is called the default constructor), you do not include the parenthesis because this would confuse the compiler. Look at this example:

 
CRectangle rect();


The compiler could interpret this in two ways. As a rectangle object:

1
2
CRectangle rect();
cout << rect.area() << endl;


Or as a function returning a CRectangle:
1
2
3
4
5
6
CRectangle rect();

CRectangle rect()
{
    return CRectangle(3, 4);
}


Because the compiler needs to be able to tell these apart, we do not use parenthesis when declaring an object that uses the default constructor. The correct, unambiguous syntax would be:

1
2
CRectangle rect;
cout << rect.area() << endl;
Thanks for confirming this and explaining this.
Topic archived. No new replies allowed.