Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "No matching constructor for initialization of" compiler error

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?

like image 568
Xavier Avatar asked Nov 12 '11 00:11

Xavier


3 Answers

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);
like image 156
celtschk Avatar answered Nov 18 '22 09:11

celtschk


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)
like image 38
jpalecek Avatar answered Nov 18 '22 09:11

jpalecek


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);
like image 1
bhuwansahni Avatar answered Nov 18 '22 08:11

bhuwansahni