mercredi 1 août 2018

Resolving circular dependencies from inheritance

Is it not possible to include the baseclass header and have it include all of its subclasses through it?

I seem to have come to an circular dependency with my base class and its subclasses.

From the program entry, I need to initialize one of the subclasses based on user input. I thought I could include the header of the base class which includes the headers of the subclasses:

main.cpp

#include "baseclass.h"

int main()
{
    ...
}

baseclass.h

#include "sub1.h"

class Base
{
    public:
        int name;
};

sub1.h

#include "baseclass.h"

class Base; // forward declaration

class Sub : public Base
{
    public:
        int age;
};

So the dependency is:

main -> baseclass -> sub1 -> baseclass -> sub1 -> etc...

If I keep the forward declaration in, g++ -std=c++11 -o prog *.cpp throws:

error: invalid use of incomplete type 'class Base'

Removing:

error: expected class-name before '{' token {

Not sure how to resolve this without putting a middle "factory" that includes all the subclass headers which each include the baseclass header.

Aucun commentaire:

Enregistrer un commentaire