Class Operators

In the first Classes (II) example of C++ tutorial, the code shows an operator being defined (lines 18-23). The example shows one Cvector parameter (Cvector param), but in the main () function, two added values are passed as a variable to c (c=a+b). How is the operator taking these two values if it only takes one parameter under the operator + definition?
Because it's a member function. a + b is equivalent to a.operator + ( b )
Forgive my ignorance, could you explain that a little further. Not seeing what you mean.
Overloaded operators are just all other functions. Member operators have the this pointer as implicit argument.
Try to see if the following example helps:
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
#include <iostream>
#include <string>
using namespace std;

struct S
{
    string name;
    S ( string name ) : name ( name ) {}

    void operator + ( const S &other ) // member operator
    {
        cout << this->name << " . operator+ ( " << other.name << " )\n";
    }

    void m ( const S &other ) // member function
    {
        cout << this->name << " . m ( " << other.name << " )\n";
    }
};

void operator - ( const S &a, const S &b ) // external operator
{
    cout << "operator- ( " << a.name << ", " << b.name << " )\n";
}

void f ( const S &a, const S &b ) // external function
{
    cout << "f ( " << a.name << ", " << b.name << " )\n";
}

int main()
{
    S first ( "first" ), second ( "second" );

    first + second;
    first . operator+ ( second );
    first . m ( second );
    first - second;
    operator- ( first, second );
    f ( first, second );

    return 0;
}
output:
first . operator+ ( second )
first . operator+ ( second )
first . m ( second )
operator- ( first, second )
operator- ( first, second )
f ( first, second )


Think + as a function called 'operator+' which can be called using a syntax which differs from normal function calls
I can't thank you enough for you detailed explanation. Finally understand it!!! The speed and efficiency of you explanation is second to none!!!! Thanks again!!!
Topic archived. No new replies allowed.