Search code examples
c++classpointersincomplete-type

"Pointer to incomplete class type is not allowed"


For some reason I cannot use the "getNotify()" function attached to the "Broker" object. I added a comment to the line that is not working(in "Publisher" class). As an error I get "Error; pointer to incomplete class type is not allowed" Please help

the "Broker" class is implemented with Singleton-Pattern Broker.h class:

#ifndef DEF_Broker
#define DEF_Broker
#include <iostream>
#include "classes.h"

using namespace std;


class Broker : Publisher
{
    static Broker *instance;
    Broker();

    public:
        static Broker* getInstance()
        {
            if(!instance)
            {
                instance = new Broker();
            }
            return instance;
        }

        void getNotify()
        {   
            for(auto sub : SubscriberList)
            {
                if(t.msg == "Hello World")
                {
                    SubCount++;
                    cout << SubCount << " - ";
                    sub->update(t.msg);
                }
                else if(t.msg == "Ping")
                {
                    cout << "Ping" << endl;
                    sub->update("Pong");
                }
            }
        }
};
Broker *Broker::instance = 0; // Null, because instance will be initialized on demand.

Broker::Broker(){}; // Private constructor so that no objects can be created.


#endif

classes.h :

#ifndef DEF_classes
#define DEF_classes
#include <iostream>
#include <list>

using namespace std;

class Broker;

class Subscriber
{
    public:
        void update(string msg)
        {
            cout << msg << endl;
        }

};

class Topic
{
    public:
        string msg;
        Topic(){};
        Topic(string msg)
        {
            this->msg = msg;
        }
};

class Publisher
{
    protected:
        list<Subscriber*> SubscriberList;
        static int SubCount; 
    
    public:
        Topic t;
        Broker *broker;// = broker->getInstance();
        Publisher(){}
        Publisher(Topic t)
        {
            this->t = t;
        };

        void AddSub(Subscriber *sub)
        {
            SubscriberList.push_back(sub);
        }

        void notify(string msg)
        {
            broker->getNotify(); // this not working
        }
};
int Publisher::SubCount = 0; // Initialize static member SubCount

#endif

Solution

  • Normally you would need to include broker.h in classes.h, however, this would create a circular dependency.

    Therefore, implement the functions of Publisher in a .cpp file and include broker.h in that file. The forward declaration in classes.h (class broker;) needs to remain.