c++inheritancefactory-method

Multi-file Factory method


There are two classes Base and Derived. Base.h:

class Base {
public:
Base* create_obj();
};

And Base.cpp :

#include "Base.h"
Base* Base::create_obj() {
   return new Derived();
};

and Derived.h :

#inlcude "Base.h"
class Derived : public Base {
};

If the two classes were in main.cpp then there would be no error. But when I put them in multiple files like above I get this error :

Cannot initialize return object of type 'Base *' with an rvalue of type 'Derived *'

Why is that? How can I fix this error?


Solution

  • You can try and do this

    // Base.h
    
    class Base {
    public:
    Base* create_obj();
    
    };
    
    // Base.cpp
    #include "Base.h"
    #include "Derived.h"
    
    Base* Base::create_obj() {
       return new Derived();
    };
    
    
    // Derive.h
    class Derived : public Base {
    };
    

    Basically I removed "Derive.h" from "Base.h" and move it to "Base.cpp". Since you don't have derived in your header there's no real need for it.

    This is called a circular dependency, where you have a header file that tries to include another file, but is itself required to be included in that header file.

    In your case this dependecy can be broken by just using the header in the .cpp file instead of the .h. In cases where you also need a reference to it in the header you can use forward declaration.