Search code examples
c++operator-overloadingvirtualoverriding

overloading virtual operator -> ()


This is just an experiment code.

struct B
{
  virtual B* operator -> () { return this; }
  void foo () {} // edit: intentionally NOT virtual
};

struct D : B
{
  virtual D* operator -> () { return this; }
  void foo () {}
};

int main ()
{
  B &pB = *new D;
  pB->foo();  // calls B::foo() !
}

I know that operator has to be called using object or reference; thus in above case does reference pB still resolute to the object of B ? Though it will not be practical, but for curiosity, is there any way to invoke D::operator -> through pB ?


Solution

  • I think it is invoking D::operator->, but the return value is being treated as a B*, so B::foo() is being called.

    This is an artifact of how covariant return types behave.