Operator Overloading

Hi guys, I have a problem. Maybe someone can help me. In the first example I tried to overloading operator +, all good, works fine. In the second example, doesn't work, my question is whyyy? Because I have an constructor in second example? And the function need to be friend or something like this?

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
62
63
64
65
66
67
68
69
70
71
72
73
  #include<iostream>
using namespace std;
class Box
{
public:
    int returnSmth(void)
    {
        return weight;
    }
    void getWeight(int wei)
    {
        weight=wei;
    }
    Box operator + (const Box& b)
    {
        Box box;
        box.weight=this->weight+b.weight;
        return box;
    }
private:
    int weight;
};
int main()
{
    int volume=0;
    Box box1;
    Box box2;
    Box box3;
    box1.getWeight(32);
    box2.getWeight(56);
    box3=box1+box2;
    volume=box3.returnSmth();
    cout<<"Total: "<<volume<<endl;
    return 0;
}




#include<iostream>
using namespace std;
class Box
{
public:
    int returnSmth(void)
    {
        return weight;
    }
    Box(int weight)
    {
        weight=weight;
    }
    Box operator + (const Box& b)
    {
        Box box;
        box.weight=weight+b.weight;
        return box;
    }
private:
    int weight;
};
int main()
{
    int volume=0;
    Box box1(65);
    Box box2(23);
    Box box3(0);
    box3=box1+box2;
    volume=box3.returnSmth();
    cout<<"Total: "<<volume<<endl;
    return 0;
}
Line 10: This is a setter. Why are you calling it getxxx?

Line 51: You're not changing the private class variable. You're changing the argument (to itself). It's not a good practice to name your arguments the same as your class variables.

For line 10 I don't have an ideea, for fun I guess, it's a problem ?
I made another example and this works fine.It's a major problem if I wrote weight=weight?
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

#include<iostream>
using namespace std;
class Box
{
public:
    int retun()
    {
        return weight;
    }
    Box(int wei)
    {
        weight=wei;
    }
    friend Box operator+(const Box& a,const Box& b)
    {
        return(a.weight+b.weight);
    }
private:
    int weight;
};
int main()
{
    int volume=0;
    Box box1(2);
    Box box2(5);
    Box box3(0);
    box3=box1+box2;
    volume=box3.retun();
    cout<<"Total: "<<volume<<endl;
    return 0;
}
Last edited on
It's a major problem if I wrote weight=weight?

It didn't work, did it?

How is the compiler supposed to know which weight you're referring to? The argument takes precedence over the class variable. So you were assigning the argument to itself and not changing the class variable.


Yes, you are right. Thanks a lot for your help. You are a good man :D
Topic archived. No new replies allowed.