Xavier
Xavier

Reputation: 9049

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?

Upvotes: 18

Views: 40572

Answers (5)

bhuwansahni
bhuwansahni

Reputation: 1844

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);

Upvotes: 1

joy
joy

Reputation: 1569

Declare Dimensions2d outside.

Dimension2d d(width, height);
TextureCoordinates result(point, d);

Upvotes: 0

Hicham
Hicham

Reputation: 979

did you write the implementation of :

TextureCoordinates(Point2D& origin, Dimensions2D& dim);

Upvotes: -1

jpalecek
jpalecek

Reputation: 47762

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)

Upvotes: 4

celtschk
celtschk

Reputation: 19721

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);

Upvotes: 18

Related Questions