c++inheritancecovariant-return-types

Returning different subtypes c++


Coming from a Java background, I'm having trouble understanding the inheritance functionality of c++. I'm trying to write a class that returns different subtypes, based on some logic inside the function. Code explaines better:

Supertype.h

class SuperType {

public:

virtual SuperType * functionA() const = 0;
};

SubTypeA.h

class SubTypeA : public SuperType{

public:

    SuperType * functionA() const override;
};

SubtypeA.cpp

SuperType * SubTypeA::functionA() const {

    if(someassertionIsTrue()){
        return new SubTypeA();
    }else{
        return new SubTypeB();
    }
}

SubTypeB.h

class SubTypeB : public SuperType{

public:

    SuperType * functionA() const override;
};

SubtypeB.cpp

SuperType * SubTypeB::functionA() const {

    if(someassertionIsTrue()){
        return new SubTypeA();
    }else{
        return new SubTypeB();
    }
}

I'm getting an error the return new SubTypeB line saying:

Cannot initialize return object of type 'SuperType *' with an rvalue of type 'SubTypeB *'

So questions:


Solution

  • If you just want to solve the compilation problem. Check if you included SubTypeB.h in SubTypeA.cpp and SubTypeA.h in SubTypeB.cpp.

    You might wanna solve the underlying problem you probably have. You want to create an object of type SubTypeB in SubTypeA and visa-versa. So the class SubTypeA need SubTypeB to compile and SubTypeB needs SubTypeA. So you have a circular dependency which is almost always a design flaw you have to solve. Since the definitions in the headers are not dependent on the other class you can get it to compile but this might change if in the future.

    How to solve this flaw depends on what you want to do and if this construct even makes sense. You could write a third class or just a function which implements the logic of functionA and creates one of the two SubTypes depending on the condition.