c++covariant-return-types

Return type of "this" in virtual functions


In the code I'm giving you, there is E that derives from C, and I have a pointer to an object of C.

#include <iostream>
using namespace std;

class C {
  public: virtual C* f(){ cout << "C::f()" << endl; return this; }
};

class E: public C {
  public: E* f(){ cout << "E::f()" << endl; return this; }
};

int main(){
  C* pc = new E;
  auto p = pc->f();
  cout << typeid(p).name() << endl;
}

When I call pc->f(), it goes to E::f() due to the virtual function, and I get it, but what is the return type of return this;?

Because this is a C*, but in the signature the method should return an E*.

If you run it, it prints:

E::f()
P1C

Solution

  • The type of p is C*, but the object it points to is an E.

    If you print the typename of *p, you get (mangled) E.

    cout << typeid(p).name() << endl << typeid(*p).name() << endl;
    

    See it on coliru

    When you call f through an E*, you get an E* back.

    int main(){
      E* pe = new E;
      C* pc = pe;
      auto p1 = pe->f();
      auto p2 = pc->f();
      cout << typeid(E).name() << endl << typeid(C).name() << endl;
      cout << typeid(p1).name() << endl << typeid(p2).name() << endl;
      cout << typeid(*p1).name() << endl << typeid(*p2).name() << endl;
    }
    

    More coliru