Frank Frank - 1 year ago 84
C++ Question

Is it possible to construct an object directly in the arguments of another constructor in c++?

I am very new to c++ and would like to know if it is possible to do something like this:

Rectangle rect(Point(0, 0), 10, 10); // doesn't work

The idea is that Rectangle takes a Point object as well as width and height parameters. The constructors look like this:

Rectangle::Rectangle(Point & point, double width, double height) {
this->point = point;
this->width = width;
this->height = height;

Point::Point(double x, double y) {
this->x = x;
this->y = y;

I can get the desired effect by doing this:

Point point(0, 0);
Rectangle rect(point, 10, 10); // this works

but I think it would be nice if I could instantiate my point directly in the arguments for a new rectangle. If this is possible, please let me know! Thanks!

Answer Source

a "regular" reference cannot bind to a temporary, only constant reference (const T&) and r-value-reference (T&&)

in your first snippet, Point(0, 0) is a temporary, so it can't be bound to Point&, but in your second snippet, Point point(0, 0); is not a temporary, so it works.

in this case, since you don't try to modify the temporary, make it bind to a constant reference :

Rectangle::Rectangle(const Point & point, double width, double height)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download