2

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?

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Lieuwe
  • 1,734
  • 2
  • 27
  • 41

1 Answers1

6
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.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Thanks for the explanation. Unfortunately the aptly named "myClass" isn't actually mine ... so I cannot change it to an explicit operator (we also have not switched to C++11 yet). – Lieuwe Jan 18 '13 at 16:29
  • @Lieuwe: That is fine. Once you switch to C++11, start adopting better idioms. For the time being, you can write something like `to_anotherClass()` or something. The idea is same : be explicit! – Nawaz Jan 18 '13 at 16:32