operator overload as a friend function.

Hello, I am currently following a book, about SDL2 game development and there is a part that I cant quite understand...

This is the code.My question is about the operator overloads.
1.Why is the += a friend function in order to work? If I remove the friend key word it gives me an error "Too many arguments for this operator function".

2.Why, if I place the function body in the .cpp file I cant use the variable name m_x or m_y in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#pragma once
#include <math.h>

class Vector2D {
public:

	Vector2D() {}
	~Vector2D() {}
	Vector2D(float x, float y) : m_x(x), m_y(y) {}

	//Add two vectors
	Vector2D operator+(const Vector2D& v2) {
		return Vector2D(m_x + v2.m_x, m_y + v2.m_y);
	}
	friend Vector2D& operator+=(Vector2D& v1, const Vector2D& v2) {
		v1.m_x += v2.m_x;
		v1.m_y += v2.m_y;
		return v1;
	}

	//Getters
	int getX() { return m_x; }
	int getY() { return m_y; }
	//Setters
	void setX(float x) { m_x = x; }
	void setY(float y) { m_y = y; }

private:

	int m_x;
	int m_y;
	
};
Last edited on
1. Yes, it is indeed nonsense (though allowed) to write it so. friend makes it a free function. Removing friend means it becomes a member function where it is not allowed to have two parameter for this function. Normally you write the (non friend) function like so:
1
2
3
4
5
Vector2D& operator+=(const Vector2D& v2) {
		m_x += v2.m_x;
		m_y += v2.m_y;
		return *this;
	}


2. If you write the function outside the class it loses the context, i.e. the compiler doesn't know that it is related with the class Vector2D
Thanks. I tried the code you showed and it worked the same way.
So is the way you showed me the way to do the operator overload?

And because I don't know what I don't know :D about C++. I use this book as a guidance for finding new operators, functions or styles of coding on c++, when I saw operator overloading it was a new thing for me.In stackoverflow and other websites it was explained in some way, but I never saw it done like this and I got confused.
Last edited on
So is the way you showed me the way to do the operator overload?
Yes, the same effect with less code. Why would you do more if not necessary?

In most cases in programming there is not just one way to do things. So it is up to you to decide what you prefer.
Topic archived. No new replies allowed.