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
The type of
pisC*, but the object it points to is anE.If you print the typename of
*p, you get (mangled)E.See it on coliru
When you call
fthrough anE*, you get anE*back.More coliru