c++ - Error: No instance of constructor matches the argument list

c++ – Error: No instance of constructor matches the argument list

c++ – Error: No instance of constructor matches the argument list

Your problem with the first version is that your compiler is trying to prevent a bug.

Your problem with the second version is that you outsmarted your compiler and successfully managed to create a bug.

Given your constructor, you want to store pointers to the float values that are passed by reference. Since your second version now calls the constructor with references to the local variables float a, b, c;, you created an instance of Vector3DHeap which references them. But as soon as getUnitVector returns, those variables no longer exist and the references stored in Vector3DHeap became dangling references.

The solution is not to store pointers inside Vector3DHeap or to create copies of the parameters:

Vector3DHeap::Vector3DHeap(float x, float y, float z)
{
    this->x = new float(x);
    this->y = new float(y);
    this->z = new float(z);
}

Make sure that you properly delete the stored floats, though.

It is good that the compiler stopped you from binding a reference to a temporary because otherwise you would have ended up with an object pointing to already destroyed objects: The expressions *x / m and similar each yield a temporary float object which will disappear at the end of the expression. Trying to bind a temporary to a non-const reference will fail.

However, I doubt that you really want to do any of that: you shouldnt use pointers unless you really know that you need to use pointers! Your constructor should probably rather look like this:

Vector3DHeap::Vector3DHeap(float x, float y, float z)
    : x(x), y(y), z(z) {
}

where the members are, of course, also of type float. getMagnitude() should return a float, too. … as should getUnitVector() return a Vector3DHeap rather than a pointer to it!

c++ – Error: No instance of constructor matches the argument list

  • (*x / m) is a temporary object.
  • Vector3DHeap(float& x, float& y, float& z) requires a non-const reference as first parameter.

You cant pass a temporary object to a function that expects a non-const reference. See https://stackoverflow.com/questions/13826897#13827042 for details why C++ does not want to allow this.

Related posts on c++  :

Leave a Reply

Your email address will not be published.