Reputation: 409
I have the following classes:
class CRectangle
{
CRectangle(string color);
CRectangle(CRectangle &origin);
/* Some more code */
};
and this other:
class CPlane
{
/* Some more code */
CRectangle boundingBox();
};
Why is it that I can do this? :
CRectangle rectangle1;
CRectangle rectangle2=rectangle1;
CRectangle rectangle3(rectangle1); //Copy constructor.
But I can't do this:
CPlane plane;
CRectangle rectangle4=plane.boundingBox();
CRectangle rectangle5(plane.boundingBox()); //Copy constructor.
If I need to me the last one work how can I do it? I suppose that maybe it has something to do with operator =
but I don't know exactly.
Edit: to fix copy constructor. error still there.
Upvotes: 3
Views: 130
Reputation: 60979
You cannot bind rvalues to a non-const
lvalue reference.
CRectangle rectangle3(rectangle1);
Here rectangle1
is a non-const
lvalue, so that's fine.
CRectangle rectangle5(plane.boundingBox());
plane.boundingBox()
is a pure rvalue (prvalue), so CRectangle&
cannot be bound to it.
Instead declare your copy constructor to take a const
reference:
CRectangle(CRectangle const&);
Or additionally declare a move constructor (if desired).
Upvotes: 3
Reputation: 10733
First syntax of your copy constructor request compiler for infinite recursion.
It should be:-
CRectangle(const CRectangle& origin);
Second, both call should work properly as both are calls to copy constrcutor.
CRectangle rectangle4=plane.boundingBox();
CRectangle rectangle5(plane.boundingBox());
Upvotes: 5