Returning null from a function returning a C ++ object

I am making an example from Head First Object Oriented Analysis and Design, but I am coding in C ++ and I don't know how to write the equivalent of "return null" from java.

Guitar getGuitar(string serialNumber)
{
    for (vector<Guitar*>::iterator it = guitars.begin(); it != guitars.end(); ++it)
    {
        if ((*it)->getSerialNumber() == serialNumber)
        {
            return **it;
        }
    }
    //return null ( java); What should return here ?!
}
+3
source share
8 answers

Java references are similar to C ++ pointers. Therefore, if you return a reference to an existing instance of Guitar or null, then your function returns the guitar *, probably what you want.

Unlike what your code actually does, a new guitar is returned, which is a copy of an existing instance.

Compared to returning the guitar, & will also return a link to an existing instance of Guitar, but will not allow you to return null.

, , * , , . , . .

+3

Guitar*. , guitars , .

+3

java " null", . . , - "", NULL - Guitar.

+1

, Java, ++, , - . , , , , , .

+1

++ . null int, ? NULL ( ), Guitar*, auto_ptr smart_ptr.

Btw. , Guitar ++ - , Java. ( ), Guitar, ...

+1

, , , , . , guitars.end().

+1

NULL - 0. NULL 0, Guitar.

, , .

+1

, ,

return the end () iterator to indicate that nothing was found
when looking for a container of guitar pointers; you could return null
to return an empty Guitar () object if none were found

Of course, you will need to change the return type accordingly.

0
source

All Articles