Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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*.
And if you run it it prints:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading