cast operator to base class within a thin wrapper derived class

Posted by miked on Stack Overflow See other posts from Stack Overflow or by miked
Published on 2010-05-21T17:25:36Z Indexed on 2010/05/21 17:30 UTC
Read the original article Hit count: 305

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about typecast-operator