Hi all there.
I was given the task to write a simple Complex Number class as an exercise for a class I'm taking. I already met my professor and all went well (:)) but I'm left with a question which I forgot to ask her: how should I handle any attempt of division by zero?
So far I managed an - ugly - solution: I declared a static bool variable for the class and set it to false. Then, at any time a division by zero is about to occurr all my class would do is return/process 0+0i as the result and set static bool div_by_zero_attempted to true. Then, in the destructor, I check its state and eventually print on screen an error message which tells that the results given by the program are not reliable. After that I reset the variable to false (just to avoid multiple error messages as long as one is enough for my purpose).
I am providing an extract from my code (the operator/ and the destructor) and I'm asking to you: is there a better/standard way to handle such cases?

Here's the code, anticipated thanks for any reply :)

Complex Complex::operator/(Complex op2) {
    Complex temp;
    if(op2.Real==0&&op2.Imaginary==0) {
        temp.Real = 0;
        temp.Imaginary = 0;
        Complex::div_by_zero_attempted = true;
    }
    else {
        temp.Real = (Real*op2.Real) + (Imaginary*op2.Imaginary);
	temp.Imaginary = (op2.Real*Imaginary) - (Real*op2.Imaginary);
	temp = temp/(op2.Modulus()*op2.Modulus());
    }
    return temp;
}

Complex::~Complex(void) {
    if(div_by_zero_attempted) {
        std::cout << std::endl << "The programm tried to process a division by zero. Any results should not be trusted." << std::endl;
        div_by_zero_attempted = false;
    }
}

Thank you for the fast reply :)
I was suspecting that it had to do with exceptions (I only heard of them) but we haven't already covered the topic in class. I'm going to study your links carefully - thank you again!

Imagine your program user's reaction:

Surprise! You waste a time because "the program tried to process a division by zero. Any results should not be trusted."...

Obviously the best design solution is: DO NOTHING. Let the program catch divide by zero exception. It's not a problem of a low-lelel class. That's why exception mechanics was invented.

Imagine your program user's reaction:

Surprise! You waste a time because "the program tried to process a division by zero. Any results should not be trusted."

Yeah you're right :P
I'm just reading the first link VernonDozier provided - I will fix my class as soon as I've finished reading and playing around a little :)

Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.