Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 220
iammilind Avatar asked Feb 02 '23 17:02

iammilind


1 Answers

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.

like image 96
Nemo Avatar answered Feb 15 '23 12:02

Nemo