Can't return nullptr to my class C++

c++, null, nullptr

Solution

You are returning `Complex`, which is not a pointer. In order to return `nullptr`, your return type should be `Complex*`.

Noticed your edit - here's what you can do:

bool Complex::sqrt(const Complex& cmplx, Complex& out) {
    if(cmplx._imag == 0)
    {
        // out won't be set here!
        return false;
    }

    out = Complex(...); // set your out parameter here
    return true;
}

Call it like this:

Complex resultOfSqrt;
if(sqrt(..., resultOfSqrt))
{ 
    // resultOfSqrt is guaranteed to be set here
} 
else
{
    // resultOfSqrt wasn't set
} 

Problem

In my method in my class, I'm checking if a value is 0 to return `nullptr`, however I can't seem to do that. ``` Complex Complex::sqrt(const Complex& cmplx) { if(cmplx._imag == 0) return nullptr; return Complex(); } ``` The error I'm getting is: `could not convert 'nullptr' from 'std::nullptr_t' to 'Complex'` I realize now, that `nullptr` is for pointers, however, my object is not a pointer, is there a way for me to set it to null or something similar?

Original source

Related problems