Question

I have a simple vector class, and I'm trying to overload the operator+ to add vectors. When it didn't work in my main program, I created a new project and stripped it down to the bare minimum, and it still didn't work.

Bare minimum code:

main.cpp

#include "vector3f.h"

int main()
{
    Vector3f* a = new Vector3f();
    Vector3f* b = new Vector3f();
    Vector3f* c = a + b;
}

vector.h

#ifndef __VECTOR3F_H__
#define __VECTOR3F_H__

class Vector3f
{
public:
    float x;
    float y;
    float z;

    Vector3f();
    Vector3f(float x, float y, float z);
    ~Vector3f();

    Vector3f operator+(const Vector3f& rhs);
}; 

#endif

vector.cpp

#include "vector3f.h"

Vector3f::Vector3f()
{
    x = 0;
    y = 0;
    z = 0;
}

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

Vector3f::~Vector3f()
{

}

Vector3f Vector3f::operator+(const Vector3f& rhs)
{
    return Vector3f(x + rhs.x, y + rhs.y, z + rhs.z);
}

Here is the compile error:

main.cpp: In function 'int main()':
main.cpp:7: error: invalid operands of types 'Vector3f*' and 'Vector3f*' to binary 'operator+'

main.cpp line 7 is Vector3f* c = a + b;.

So my question, as is expected on Stack Overflow, is: what am I doing wrong?

Side note: I have a very lame IDE and the problem may be a faulty compiler, though I don't expect this to be the case.

Any help is appreciated. Thanks in advance!!

Was it helpful?

Solution

You dynamically allocated your Vectors, and the + operator is not defined for pointers to vectors.

So you need to change:

 Vector3f* a = new Vector3f();
 Vector3f* b = new Vector3f();
 //... assigning of and b
 Vector3f* c = a + b;

To

Vector3f* a = new Vector3f();
Vector3f* b = new Vector3f();
Vector3f* c = new Vector3f();
*c = *a + *b;

OTHER TIPS

I'm surprised this hasn't been said, but why are you using pointers at all?

Vector3f a;
Vector3f b;
Vector3f c = a + b;

No more trying to add pointers. No more awkward syntax. No more memory leaks.

Apart from this, you have some other things you should change:

  • __VECTOR3F_H__ is a reserved identifier.
  • You should get used to using constructor initializer lists (: x(0), y(0), z(0) and : x(x), y(y), z(z)) instead of assigning to data members after they've already been initialized.
  • You don't need a destructor here, as one will be provided for you.
  • operator+ should be implemented using operator+=, which you should also provide.

Try this ,

 Vector3f c = *a + *b;

Now this will overload your operator else it was an pointer addition

You have overloaded objects not object pointers. Use this

Vector3f c = (*a) + (*b);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top