tags:

views:

70

answers:

3

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

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?

+3  A: 

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.

Konrad Rudolph
Or assign a default value to the parameter.
jasonline
+3  A: 

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.

Thorsten79
Its the mess im in. What about user defined objects as parameters? Will NULL still be the on to use?
Jason94
I don't know if I understand your comment question correctly. If you use pointers you can set them to NULL as of the C++ language definition. If you use references, you are out of luck because there are no valid ways to make a reference null (you CAN do it, but only with dirty tricks and loss of all your C++ karma). Again, I would recommend to redesign as far as possible even if you are in a mess now.
Thorsten79
A: 

It's the mess I'm in

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

FredOverflow