c++classthisc++20derived-class

How can I return a derived class instance from a base class function


Let's say I have two classes. base and derived_from_base. base will contain a lot of functions that will control certain aspects of base and the derived classes will use. However, I would like to make it so I can chain calls to these functions.

class data_class {};

class base {
public:
  base* add_data(data_class* data) {
    m_Data = data;
    return this;
  }

private:
  data_class* m_Data;
};

class derived_from_base : public base {
  void custom_function() {}
};

int main() {
  data_class* someData = new data_class();

  // "myClass" has none of the data after this return
  derived_from_base* myClass = derived_from_base().add_data(someData);

  derived_from_base* myOtherClass = derived_from_base();
  // The data is available in this class now.
  myOtherClass.add_data(someData);
}

I have tried passing the derived classes this pointer to the base class but it has yielded the same results.


Solution

  • One way things like this are sometimes accomplished is via the CRTP-idiom.

    In your case this would look something like this:

    class Base {
    private:
      // ...
    public:
      Base* add_data(data_class* data) {
        // implementation ...
      }
    };
    
    template <typename T>
    class BaseCRTP : public Base {
    public:
      T* add_data(class_data* data) {
        return static_cast<T*>(Base::add_data(data));
      }
    };
    
    class Derived : public BaseCRTP<Derived> {
    public:
      void custom_function() {}
    };
    
    int main() {
      Derived derived;
      derived.add_data(new class_data())->custom_function();
    }
    

    This is not the best style in several points. For one, it would be better to return a reference, not a pointer. So *this, not this.

    Anyway, by introducing an intermediate base class template you offload the code-reuse to a template and have to write a wrapper only once.