// By using structure :
struct complex {
float real;
float imag;
};
complex operator+(complex, complex);
main() {
complex t1, t2, t3;
t3 = t1 + t2;
}
complex operator+(complex w, complex z) {
statement 1;
statement 2;
}
// By using class :
class complex {
int real;
int imag;
public:
complex operator+(complex c) {
statement 1;
statement 2;
}
main() {
complex t1, t2, t3;
t3 = t1 + t2;
}
While using structure, the overloaded function can accept two arguments whereas while using class the overloaded function accepts only one argument, when the overloaded operator function is a member function in both cases i.e in struct as well as in class. Why does this happen?
That has nothing to do with classes vs. structs. It's about member vs. nonmember.
Classes and structs in C++ differ solely bu their default accessibility level for members and bases (public for structs, and private for classes). Other than this, there is no difference at all.
When overloading operators, you almost always have the choice of defining an operator as a member or as a freestanding function. There are only 4 operators that have to be members. These are: ()
, []
, ->
, and =
(as to why, see this question of mine). For the rest, the choice is yours.
This excellent FAQ entry explains (among other things) how to choose between member vs. nonmember.
To answer your core question: In case of member function, the first agument is *this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With