Search code examples
c++class-constructors

Member initialization in constructors


Can someone please tell, in this code how to declare the constructor such that when the object is instantiated, height is initialized with passed value while width is always default (2 in the case below).

class rectangle{
    int width, height;
public:
    //  rectangle(int w = 1, int h = 1): width(w), height(h){}
    rectangle(int w = 2, int h=1): width(w) {height = h;}
    int getW(){return width;}
    int getH(){return height;}
};
int main()
{
    rectangle r1(1);
    rectangle r2(2);
    rectangle r3(4);
    rectangle r4(5);
    cout << "w = " << r1.getW() <<" h = " << r1.getH() << endl;
    cout << "w = " << r2.getW() <<" h = " << r2.getH() << endl;
    cout << "w = " << r3.getW() <<" h = " << r3.getH() << endl;
    cout << "w = " << r4.getW() <<" h = " << r4.getH() << endl;
}
Output with above code:
w = 1 h = 1
w = 2 h = 1
w = 4 h = 1
w = 5 h = 1

Can someone tell me how to declare the constructor so that the output is like below (I want to declare the object with only one parameter)?

w = 1 h = 1
w = 1 h = 2
w = 1 h = 4
w = 1 h = 5

Solution

  • The wording in your question is a bit unclear. It sounds like you want to completely ignore the width argument, and just make the width 2, while the height is optional, and defaults to 1. If that is the case, then you can simply do this:

    rectangle(int, int h=1) :width(2), height(h) {}
    

    But my mind reading skills tell me that is not really what you want (mainly because it's a stupid thing to do). I have a hunch that you simply worded your question wrong, and that you actually want something like this:

    rectangle(int w, int h) :width(w), height(h) {} // handles 2 arguments
    rectangle(int h=1) :width(2), height(h) {}      // handles 0 or 1 arguments
    

    This configuration allows three call signatures.

    • 2 arguments, first goes to width, and the second goes to height.
    • 1 argument, which goes to height, and width becomes 2
    • 0 arguments, width becomes 2, height becomes 1