Seg Fault for Complex Number Overloading Operator

I am trying to make a Complex Number class and I can't seem to figure out why I get a seg fault whenever I try to display the number when real and imaginary are both zero or if only the imaginary part is zero. Take a look at my code and let me know what you think.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
in main.cpp:
 Complex a;
 Complex b(3.5, 2.1);
 Complex c(0.0, 2.1);
 Complex d(3.5, 0.0);

in complex.cpp
 ostream & operator << (ostream & out, const Complex & rhs)
 {
   out << rhs.getReal();
   if (rhs.getImaginary() != 0.0)
   {
      out << " + " << rhs.getImaginary() << "i";
   }
 }



When I output Complex a and d they both seg fault. Any ideas? Let me know if you need more code!

Thanks!
Last edited on
There is too little code to even guess what's wrong.
Just my 1 cent worth:+) , might not have anything to do with your problem

Be careful with equality comparison with FP numbers, they are not exact. It might work when the object is created with 0.0, but it won't work in this scenario:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double K = 0.1; // 0.0999999999999997 possibly, could be 1.0 + 3e-15
double L = 10.0 * K; // 0.999999999999997
double M = L - 1.0;  // -3e-15

if (M == 0.0) {} // false

if (M != 0.0) {} // nearly always true

const double PRECISION = 1e-4;

if (std::abs(M) < PRECISION) {}  // true M is near enough to zero for our purposes

double R = 2.0;
double S = 20.0 * K;

if (std::abs(R - S) < PRECISION)  {} // true R and S are near enough to equal for our purposes 


With your problem, can we see all of your constructors and getImaginary ,then Peter can help you :+)
Last edited on
you promised to return an ostream&, but you didn't.
Topic archived. No new replies allowed.