18

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?

1
  • Where's the definition of the constructor? All I see is the declaration. Commented Nov 12, 2011 at 0:28

5 Answers 5

18

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

0

Declare Dimensions2d outside.

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

Comments

-1

did you write the implementation of :

TextureCoordinates(Point2D& origin, Dimensions2D& dim);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.