Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance: Function that returns self type?

Tags:

c++

Let's say I have two classes:

class A
{
    public:
    A* Hello()
    {
        return this;
    }
}

class B:public class A
{
    public:
    B* World()
    {
        return this;
    }
}

And let's say I have an instance of B class like so:

B test;

If I call test.World()->Hello() that would work fine. But test.Hello()->World() would not work since Hello() returns A type.

How could I make Hello() return the type of B? I don't want to use a virtual function since we have over 20 different classes inheriting A.

like image 254
Grapes Avatar asked Aug 01 '12 14:08

Grapes


1 Answers

You can use CRTP, the curiously recurring template pattern:

template<class Derived>
class A {
public:
    Derived* Hello() {
        return static_cast<Derived*>(this);
    }
};

class B : public A<B> {
public:
    B* World() {
        return this;
    }
};

   
int main() {
    B test;
    test.World()->Hello();
    test.Hello()->World();
}
like image 180
mfontanini Avatar answered Nov 11 '22 10:11

mfontanini