Search code examples
c++inheritanceconversion-operator

What does it mean that the conversion operator is "still valid" in a derived class


class Game {
  class Other {}; // Nested class
  // Automatic type conversion:
  operator Other() const {
    cout << "Game::operator Other()\n";
    return Other();
  }
};    
class Chess : public Game {};
void f(Game::Other) {}
int main()
{
    Chess d;
    f(d);
}    

I'm reading the "thinking in c++" chapter 14--functions that don't automatically inherit. The above code fragment is an example given by Eckel. And Eckel said:

"Because of all these rules about rewriting functions that handle object creation, it may seem a little strange at first that the automatic type conversion operator is inherited. But it's not too unreasonable-if there are enough pieces in Game to make an Other object, those pieces are still there in anything derived from Game and the type conversion operator is still valid(even though you may in fact want to redefine it)."

I don't understand what Eckel tries to say. Can anyone explain it more detail?

Thanks


Solution

  • He is saying that, unlike some other similar things, type conversion operators are automatically inherited by derived classes.

    His argument for why this behaviour is reasonable is that if you can construct an Other from a Game, you can also construct an Other from anything that "is a" Game (i.e. a derived class).