'in operator overloading(binary) how does object access something already assigned
// C++ program to overload the binary operator +
// This program adds two complex numbers
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}
void input() {
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
// Overload the + operator
Complex operator + (const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
void output() {
if (imag < 0)
cout << "Output Complex number: " << real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main() {
Complex complex1, complex2, result;
cout << "Enter first complex number:\n";
complex1.input();
cout << "Enter second complex number:\n";
complex2.input();
// complex1 calls the operator function
// complex2 is passed as an argument to the function
result = complex1 + complex2;
result.output();
return 0;
}
In this program whatever is passed in complex1 directly calls the operator function so the value of complex1 is stored in real and imaginary.
If now real and imaginary are already holding a value, how can an object of class(like temp,obj) is able to access real and imaginary and then assing all three different values at same time?
Thankyou!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
