Operating Overloading

Hello,

I was exploring C++ for the first time and trying to understand few concepts. I came across this topic: Operator Overloading and understood the basics that this is used to do +, -, *, /, <= operations. So, I wanted to understand if the following is the code to add two different numbers.
Ref - https://www.interviewbit.com/cpp-interview-questions/


class complex{
private:
float r, i;
public:
complex(float r, float i){
this->r=r;
this->i=i;
}
complex(){}
void displaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
return complex(r+c.r, i+c.i);
}
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}
First, please use code tags (and logical indentation) when posting code. See https://www.cplusplus.com/articles/jEywvCM9/


You have the operator+ as member of the class. That is possible.
It can be a standalone function too. Then it uses public interface of the operands.
Scott Meyers suggests non-friend non-members: https://embeddedartistry.com/fieldatlas/how-non-member-functions-improve-encapsulation/

There are also compound assignment operators. See
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Assignment_operators
https://en.cppreference.com/w/cpp/language/operator_assignment
They tend to be members, because they modify the left operand.

Standalone operator+ is quite easy to implement with operator+=.
Last edited on
Member functions that don't change class variables should be marked as const - so that they'll work with const variables.

You can also overload operator<< so that it works with a specified type. Consider:

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
#include <iostream>

class complex {
private:
	float r {}, i {};

public:
	complex(float r_, float i_) : r(r_), i(i_) {}
	complex() {}

	complex operator+(const complex& c) const {
		return complex(r + c.r, i + c.i);
	}

	friend std::ostream& operator<<(std::ostream& os, const complex& c) {
		return os << '(' <<  c.r << ',' << c.i << ')';
	}
};

int main() {
	const complex a(2, 3);
	const complex b(3, 4);
	const auto c {a + b};

	std::cout << "c is " << c << '\n';
}

Last edited on
@seeplus: the std::cout on line 16 ... os ?

It is also possible to have non-friend non-member operator<< that is mere wrapper for
member function that does the actual work:
1
2
3
4
5
6
7
8
9
10
11
12
13
class complex {
  // ...
  std::ostream& displaydata( std::ostream& os ) const {
    os <<”real part = “<<r<<endl;
    os <<”imaginary part = “<<i<<endl;
    return os;
  }
  // ...
};

std::ostream& operator<<( std::ostream& os, const complex& c ) {
  return c.displaydata( os );
}
@seeplus: the std::cout on line 16 ... os ?


Whoops....... It should be, of course, :

1
2
3
friend std::ostream& operator<<(std::ostream& os, const complex& c) {
		return os << '(' <<  c.r << ',' << c.i << ')';
	}

Topic archived. No new replies allowed.