I have a class which I try to initialize but get the error "No matching constructor for initialization of 'TextureCoordinates'";
Class which I'm trying to initialize:
class TextureCoordinates
{
public:
TextureCoordinates(){};
TextureCoordinates(Point2D& origin, Dimensions2D& dim);
Point2D getOrigin() const {return origin;};
Dimensions2D getDim() const {return dim;};
private:
Point2D origin;
Dimensions2D dim;
};
Line with compiler error:
TextureCoordinates result(point, Dimensions2D(width, height));
Definition of constructor:
TextureCoordinates::TextureCoordinates(Point2D& origin, Dimensions2D& dim):
origin(origin), dim(dim) {}
Any ideas what I'm doing wrong?
Your constructor takes the arguments by non-const reference, but you pass a temporary object (Dimensions2D(width, height)
) to it. Temporaries, even non-const ones, do not bind to non-const references.
Solution, make your constructor take const references (it shouldn't modify the passed objects anyway):
TextureCoordinates(Point2D const& origin, Dimensions2D const& dim);
TextureCoordinates result(point, Dimensions2D(width, height))
The second parameter is an rvalue that cannot be bound to lvalue reference the constructor expects:
TextureCoordinates(Point2D& origin, Dimensions2D& dim);
You can fix it by changing the signature of the constructor to
TextureCoordinates(Point2D& origin, const Dimensions2D& dim);
TextureCoordinates(Point2D& origin, Dimensions2D&& dim); // alternative for c++11
(if you can) or making the parameter a variable
Dimension2D dim=Dimensions2D(width, height);
TextureCoordinates result(point, dim)
Temporary variables cannot be passed as a reference in C++ because then you can change the value of a temporary object in the function that is soon going to disappear!! No such problem exists for reference to constants..... So your function definition should be like
TextureCoordinates(Point2D const& origin, Dimensions2D const& dim);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With