0

Let's say I have the classes:

class Rect {
    int w, l;
    Rect(width, length) : w(width), l(length) {}
}

class Box {
    Rect &r; int h;
    Box(int width, int length, int height);
}

For the sake of argument, I do not offer default values for width an height. Mainly because this is meant as a simplified example of what I'm actually doing.

Is there any where I can use the constructor of multiple arguments Rect(width,height) to explicitly initialize Rect &r? I know what I would do if the constructor had a single argument, I would simply go:

Box(int width, int length, int height) : r(loneArgument), h(height)

But now, I need to explicitly initialize with multiple arguments. However:

Box(int width, int length, int height) : r(width, height), h(height)

results in a compiler error. While we're at it, so does

Box(int width, int length, int height) : r(Rect(width, height)), h(height)

with the error

error: non-const lvalue reference to type 'Rect' cannot bind to a temporary of type 'Rect'

Any idea how I can get around this? Or at least any good reasons why this may be bad practice?

I understand that I can easily give default values for width and height to solve my issue, but I'm using a simpler code and in my actual code, default values wouldn't make any sense, since the actual object I want to define requires using a multiple input constructor.

So any ways to resolve this?

Osama Kawish
  • 312
  • 1
  • 5
  • 15
  • 1
    Whether the constructor has one, many, or a hundred arguments is competely irrelevant. This constructor must initialize its reference class member, as a reference to some other `Rect` object, and ***not*** create a new object, as you're trying to do. That's what a reference means: a reference to some other, existing object. If you're trying to construct a new object, `Rect` would obviously be a non-reference class member. – Sam Varshavchik Nov 24 '19 at 14:37
  • @Evg I guess this is better explained with my context. I'm making a vector graphics illustrator app like InkScape in Qt. I need a constructor for a `Node`. The node is accessed in the `QGraphicsView` when clicked. It has a reference to the curve its attached to. – Osama Kawish Nov 24 '19 at 14:40
  • @SamVarshavchik Fair enough. I think that was what I was trying to do. In any case, I guess my code needs a lot of fixing then. But thanks for the response. – Osama Kawish Nov 24 '19 at 14:42
  • 2
    @MadManiac, if `Rect` is stored somewhere else, pass a reference to it into the `Box` constructor. If is part of `Box` itself, it should be its non-reference member. You can't have both alternatives at the same time. Technically, you can with `std::variant> r;`, but I don't think that's what you really want. – Evg Nov 24 '19 at 14:45
  • @Evg Fair enough. – Osama Kawish Nov 24 '19 at 14:48

0 Answers0