Search code examples
c++qtqt5forward-declaration

C++ forward declaration in Qt


I have 3 classes which depend on each other:

class Channel
{
public:

enum ChannelType {
    DIMMER, RED, GREEN, BLUE, STROBE
};

Channel(ChannelType type);
const ChannelType type;

void x(Fixture fixture);
};

class Fixture
{
    public:
    Fixture(int channel, FixturePattern pattern);

    Channel getChannel(const Channel::ChannelType);

    private:
        const int channel;
        FixturePattern pattern;
};

class FixturePattern
{

public:
    FixturePattern(QList<Channel> channels);
    Channel getChannel(Channel::ChannelType type);

private:
    QList<Channel> channels;
};

These classes are in separate header files. I tried to connect them with #include but I always end up with incomplete types or the XY was not declared in this scope error. Can someone explain me what I am doing wrong?
I didn't add the #includes since I completely screwed it up yesterday. Recently I already found a question with this topic but I don't want to put it in the same file. Is it possible?


Solution

  • Without going into a lot of details you should use forward declaration for your classes. You'll need to modify your code to be able to do it. The code should look something like this. I didn't test it but it should work.

    class Fixture; // the forward deceleration 
    class Channel
    {
    public:
    
    enum ChannelType {
        DIMMER, RED, GREEN, BLUE, STROBE
    };
    
    Channel(ChannelType type);
    const ChannelType type;
    
    void x(const Fixture &fixture); // or void x(Fixture *fixture);
    };
    
    #include "FixturePattern.h" 
    class Fixture
    {
        public:
        Fixture(int channel,const FixturePattern &pattern);
    
        Channel getChannel(const Channel::ChannelType); 
    
        private:
            const int channel;
            FixturePattern pattern;
    };
    
    #include "Channel.h"
    class FixturePattern
    {
    
    public:
        FixturePattern(QList<Channel> channels);
        Channel getChannel(Channel::ChannelType type);
    
    private:
        QList<Channel> channels;
    };