Lieuwe
Lieuwe

Reputation: 1840

Conversion operator issues

I stumbled upon this "problem" earlier today.

I have this class and it contains a conversion operator. Something like:

class myClass {
public:
    ...

    operator anotherClass*() { return anotherClassPtr; }

    ...
}

Now this all works well .. until I made this silly mistake:

void yetAnotherClass::foo(myClass* _p_class) 
{
  ...

  anotherClass* lp_anotherClass = (anotherClass*)_p_class;

  ...
}

And it took me a long time to figure out why the lp_AnotherClass ptr was set to something non-zero whilst I was sure that the anotherClassPtr in _p_class was 0.

Is there anything I could have added to myClass that would have prevented me from making this mistake? (i.e. the compiler would have spat out some error) Is it possible to prevent an object ptr being cast to something else?

Upvotes: 2

Views: 115

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361812

anotherClass* lp_anotherClass = (anotherClass*)_p_class;

First of all, you should not use C-style cast. Use C++-style cast. That would have saved your time, as the compiler would tell you the problem immediately:

auto* lp_anotherClass = static_cast<anotherClass*>(_p_class); //ERROR

Secondly, prefer using explicit conversion function:

explicit operator anotherClass*() { return anotherClassPtr; }

Why I suggest explicit conversion function, because it avoids subtle bugs arises from implicit conversions, and additionally, it increases the code readability!

Note that explicit conversion function is a C++11 feature.

Upvotes: 6

Related Questions