开发者

Can't I send NULL as a parameter with a constructor?

Lets say i have a Shape object that has a constructor like this:

Shape( width, height, radius, depth )

Now, I just have a silly rect so i dont need redius and depth... is it okey to do

开发者_Go百科
Shape myRect(50, 50, NULL, NULL) ?

I know its not the best idea and I should use inheritance and stuff but this is the mess im in so can i use NULL like this?


Depends on what types radius and depth are. If they are integers, you have to use an out-of-bound value like -1 to indicate "not set" (out-of-bound could also be 0 if you declare it that way). If they are pointers, NULL could be used.

Actually what you describe is a common example of bad inheritance, and it's used in OOP teaching to show why not everything should be inherited. Shapes are just too different for this.


can i use NULL like this?

No. NULL is a pointer value. In fact, the code will even compile (in C++) but it will just pass the value 0 to the int arguments, not a null-pointer, since the arguments obviously aren’t pointers.

The solution is to provide an overloaded constructor that takes only two arguments:

class Shape {
    // Your “normal” constructor
    Shape(int w, int h, int r, int d) {
        // …
    }

    // Overload taking only two arguments
    Shape(int w, int h) {
        // …
    }
};

And call it like this:

Shape myrect(50, 50); // Calls second constructor.

Of course, the design will still be bad as you’ve noticed yourself. One class does not fit them all.


It's the mess I'm in

There is a counter-measure against this kind of mess which is called Refactoring.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜