Search code examples
c++typecast-operator

cast operator to base class within a thin wrapper derived class


I have a derived class that's a very thin wrapper around a base class. Basically, I have a class that has two ways that it can be compared depending on how you interpret it so I created a new class that derives from the base class and only has new constructors (that just delegate to the base class) and a new operator==. What I'd like to do is overload the operator Base&() in the Derived class so in cases where I need to interpret it as the Base.

For example:

class Base
{
  Base(stuff);
  Base(const Base& that);
  bool operator==(Base& rhs); //typical equality test
};

class Derived : public Base
{
  Derived(stuff) : Base(stuff) {};
  Derived(const Base& that) : Base(that) {};
  Derived(const Derived& that) : Base(that) {};
  bool operator==(Derived& rhs); //special case equality test
  operator Base&()
  {
    return (Base&)*this;  //Is this OK?  It seems wrong to me.
  }
};

If you want a simple example of what I'm trying to do, pretend I had a String class and String==String is the typical character by character comparison. But I created a new class CaseInsensitiveString that did a case insensitive compare on CaseInsensitiveString==CaseInsensitiveString but in all other cases just behaved like a String. it doesn't even have any new data members, just an overloaded operator==. (Please, don't tell me to use std::string, this is just an example!)

Am I going about this right? Something seems fishy, but I can't put my finger on it.


Solution

  • Since your Derived is derived from Base publically, your Derived is already convertible to Base &. There's no need to implement anything extra.

    Moreover, when it comes to conversion operator itself, whether you are doing it right or wrong is a moot question, since your conversion operator will never be used anyway. The derived-to-base conversion is always handled by the built-in means. If you provide your own operator for the conversion (as you do above) it will be ignored anyway.

    I don't get though how you were planning to use if to solve the original problem with different comparison approaches.