0

How can I write a method toDerived() (instead or additionally to a constructor) that converts a base class object to a derived class object?

With the following setup I get the error "Incomplete result type 'Derived' in function definition of 'toDerived()'".

// base.h
#ifndef BASE_H
#define BASE_H

#include "derived.h"

class Derived;
class Base { 
public:
  // constructor etc.

  Derived toDerived() const { /* ... */ };
};

#endif
// derived.h
#ifndef DERIVED_H
#define DERIVED_H

#include "base.h"

class Derived : public Base { 
public:
  // constructor etc.
};
fakl
  • 127
  • 7
  • You can't change the type of an existing object. –  Aug 28 '22 at 19:14
  • Your `Derived` requires `Base` to be defined, so it includes it. Your `Base` requires `Derived` to be defined, in order to be defined in order to implement the method. Even the most advanced quantum computer cannot solve the basic "which came first, the chicken or the egg" question. In `Base` you need to get rid of the include, forward-declare the `Derived`, and declare the class method, then define it in the derived header file, or some `.cpp` file that includes them. – Sam Varshavchik Aug 28 '22 at 19:17
  • 2
    That your `Base` needs to clone to `Derived` is a pungent design smell. I suspect the *real* problem you're trying to solve is a container of polymorphic instances based on `Base` that should have been stored as references or pointers, but is sliced into `Base`s on insertion instead. Yeah, I know it's a leap, but it's the only X that fits this seemingly XY problem. – WhozCraig Aug 28 '22 at 19:17
  • Ok, thanks, that sounds valid to me! In this case I will just write a constructor: ```Derived(Base& base)````. This solved my problem, but I thought it would be nice to have a method for that as well. – fakl Aug 28 '22 at 19:19
  • 1
    Normally a base class should not know about any of its derived classes. There are exceptions but they need to be justified. – n. m. could be an AI Aug 28 '22 at 19:20
  • For completeness I'd include that it's doable in `Base` as well, if `toDerived()` is a template function. – lorro Aug 28 '22 at 22:26

0 Answers0