Operator overloading basics

Hi peeps,

I'm really struggling to get my head around operator overloading.

Please consider the following code:

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
class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Add Cents + Cents
    friend Cents operator+(const Cents &c1, const Cents &c2);
 
    int GetCents() { return m_nCents; }
};
 
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
}
 
int main()
{
    Cents cCents1(6);
    Cents cCents2(8);
    Cents cCentsSum = cCents1 + cCents2;
    std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;
 
    return 0;
}


Could you tell me if this is a correct assessment:

In the function starting at line 16, what it's saying is basically:

"people, if an object Cents is declared which tries to add two other Cents objects together, it's ok, just do it"

And in line 26, we try to do just that. So then the compiler says:

"Ok, that was explained to me in the function "Cents operator+(const Cents &c1, const Cents &c2)", so it's ok, replace this Cents object (cCentsSum) with the returned Cents object".

Is it someting like that?

Sorry in advance if i'm talking gibberish!
Last edited on
Your terminology is a bit off, but you have the right idea. When you try to use an operator with one or more user-defined types, the compiler looks around for an appropriate handler such as the one on line 16. The rules are the same as for any other form of Argument Dependent Lookup (ADL) - if you're not familiar with ADL, just Google it.
Many thanks, could i ask you to re-write my assessment with the correct terminology?
Last edited on
Line 16 is just a normal function definition, the only difference being that the function has a special name.

On line 26, the compiler sees the expression like this: Cents cCentsSum (operator+(cCents1, cCents2)); - that is valid code that will compile just the same as your current code. Writing it this way makes the ADL more obvious, but is obviously harder to read otherwise.

EDIT: an old example I made of ADL in action: https://ideone.com/IdIquW
Last edited on
Topic archived. No new replies allowed.