Skip to content

if (obj) : if statements and operator overloading #1010

@GuillaumeDua

Description

@GuillaumeDua

Maybe related to issue #1006 ,
I notice during my last training session that newcomers to C++ are quite confused about if statements and operator overloading.

Maybe the guideline could describe a best-practice for this purpose.

For instance (see https://godbolt.org/g/X4R3Pc for complete code) :

struct object1
{
    inline operator bool() const noexcept;
};

struct object2
{
    inline operator bool() const noexcept;
    inline bool operator!() const noexcept;
};

void    use_objects()
{
    object1 obj1;
    if (!obj1)      // call operator bool(), then operator!(bool)
        /* deal with invalid object */ ;
    object2 obj2;
    if (!obj2)      // call object2::operator!()
       /* deal with invalid object */  ;
}

I also see students that define overload functions like :

bool object::operator!=(int i)

In order to write such synthax :

if (obj != 0)
   /* deal with invalid object */;

Also, many libraries use :

if (!!obj)
 ;

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions