operator overloading, no acces to private members?

Hallo,

I am currently learning C++. But now I wrote some code to overload operatos. The first operator- is not working and returns "No access to private members ..."?! The second operator+ is working properly.

I really can not spot my misstake here ... hopefully you can help me out.


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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

class burrito
{
		burrito operator-(const burrito& b) {
                burrito result;
		result = this-> x - b.x;
		result = this-> y - b.y;
		return result;
	}

	friend burrito operator+(burrito& a, burrito& b) {
		burrito ergebnis;
		ergebnis.setx(a.getx() + b.getx());
		ergebnis.sety(a.gety() + b.gety());
		return ergebnis;
	}

private:
	static int varstat;
	int x;
	int y;

public:
	burrito() : x(1), y(1) {
	varstat++;
}
	burrito(int x, int y) : x(x), y(y) {
	varstat++;
}

	static int getstat() {
		return varstat;
	}
	int getx() {
		return x;
	}
	int gety() {
		return y;
	}

	void setx(int x) {
		burrito::x = x;
	}
	void sety(int y) {
		burrito::y = y;
	}
};

int burrito::varstat = 0;

int main() {

	burrito first(1,5);
	burrito second(2,9);
	burrito third;
	third = first + second;
	cout << "1 . third.x: " << third.getx() << " third.y: " << third.gety() << endl;
	third = third - second;
	cout << "2. third.x: " << third.getx() << " third.y: " << third.gety() << endl;

}
Last edited on
You have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class burrito
{
  burrito operator-(const burrito& b);
  friend burrito operator+(burrito& a, burrito& b);
private:
  static int varstat;
  int x;
  int y;

public:
  burrito();
  burrito(int x, int y);
  static int getstat();
  int getx();
  int gety();
  void setx(int x);
  void sety(int y);
};

Members of a class are private by default.
Members of a struct are public by default.

Therefore, the burrito operator-(const burrito& b); is private.
The main cannot access private members.


The friend burrito operator+(burrito& a, burrito& b); is not a declaration of a member.
It just tells that a standalone function burrito operator+(burrito& a, burrito& b); has access to all members of burrito.

It does not need to be a friend, because it uses public interface of burrito (get*, set*).
As friend, it can:
1
2
3
4
burrito operator+(burrito& a, burrito& b) {
  burrito ergebnis( a.x + b.x, a.y + b.y );
  return ergebnis;
}

It is better to have non-friend non-members.


A canonical approach to these operators is to have operators += and -= as members and
operators + and - as non-friend non-members. Implement latter with former. For example:
1
2
3
4
burrito operator+(burrito a, const burrito& b) {
  a += b;
  return a;
}
Last edited on
Thanks, helped me out alot 😊
Topic archived. No new replies allowed.