Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance of methods but wrong return types (automatic casting? typeid(*this) ?)

I have a BaseClass with a method that returns a class object, and i have a DerivedClass. Now when I have a DerivedClass object and call the method defined in the BaseClass, the returning value is ob type BaseClass, and unfortunately not of type DerivedClass.

class BaseClass {
public:
  typeof(*this) myMethod1() {return *this;} // nice if that would work
  BaseClass& myMethod2() {return *this;}
  BaseClass myMethod3() {return BaseClass();}
};
class DerivedClass : public BaseClass {};

DerivedClass tmp;
tmp.myMethod1();
tmp.myMethod2();
tmp.myMethod3();
// all three methods should return an object of type DerivedClass,
// but really they return an object of type BaseClass

So what I wish to achieve is to use methods of the superclass, but with return types of the derived class(automatic casting?). myMethod1() was the only thing I could think of, but it doesn't work.

I've searched but didn't find anything satisfying.

like image 819
smat88dd Avatar asked Jun 05 '26 16:06

smat88dd


1 Answers

You would like to use the CRTP (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) pattern :

template <class Derived>
class BaseClass {
public:
  Derived *myMethod1() {return static_cast<Derived *>(this);}
  Derived& myMethod2() {return static_cast<Derived&>(*this);}
};
class DerivedClass : public BaseClass<DerivedClass> {};

DerivedClass tmp;
tmp.myMethod1();
tmp.myMethod2();
like image 59
AntiClimacus Avatar answered Jun 08 '26 09:06

AntiClimacus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!