Problems with personally constructed complex number class

78 views Asked by At

I am having trouble figuring out why my complex number class isn't adding correctly or working exactly how I want it to. When I add two complex numbers together I get something really weird that isn't supposed to be. I keep trying to figure out what's wrong, but can't quite figure it out. I need to keep the structure because I am going to use it for another purpose.

#include <iostream>
#include <cmath>

using namespace std;

class ComplexNumber{
private:
    double real, imag;
public:
    ComplexNumber(double i,double j){
    real = i;
    imag = j;}

    ComplexNumber add(ComplexNumber c){
    real += c.real;
    imag += c.imag;
    }

    ComplexNumber squared(){
    real = (pow(real,2) - pow(imag,2));
    imag = 2*real*imag;
    }

    double abs() {
    return sqrt(real*real + imag*imag);
    }
    void print(){
        char sign = (imag<0) ? '-' : '+';
        cout<<real<<" "<<sign<<" "<<(imag>0 ? imag : -imag)<<'i'<<endl;
    }

};

int main() {
ComplexNumber c1(3,4), c2(1,1);
ComplexNumber c3=c1.add(c2);
c3.print();
return 0;
}
2

There are 2 answers

1
juanchopanza On

Your add member function promises to return a ComplexNumber but it doesn't. You then attempt to use the return value, invoking undefined behaviour. squared is similarly broken.

You need to figure out whether you want add to implement the behaviour of operator += or +. In the first case, you'd need to return a reference to the object being modified:

ComplexNumber& add(ComplexNumber c)
{//          ^
  real += c.real;
  imag += c.imag;
  return *this;
}

In the second case, do not modify the object but create a new one and return it:

ComplexNumber add(ComplexNumber c)
{
  return Complex(real + c.real, imag + c.imag);
}

Note that in this case it may make sense to use a non-member function instead.

I suggest looking at std::complex for an example of a good implementation.

1
CHKingsley On

As declared, your Add function should end with:
return ComplexNumber(real,imag);

But that makes me wonder -- it does not sound like "add into", it sounds like it would be "add args and this number and return a new Complex." You can clarify your interface a bit. If "Add" means "Add into" then it might be void and return nothing. Or it might return itself, so you can do more with it after adding into it. (That's what "+=" does.) If that is what you are looking for, you would return ComplexNumber& (a reference to ComplexNumber) and end with:
return *this;

In any case, why did you compiler not warn you when a function did not return with a value? Did you set the warning level to "never warn me"? Turn your compiler warnings up. Not returning a value when the function is declared to have a result is a basic error, it shouldn't even be just a warning.