Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, how can I hold a list of an abstract class?

I have two implemented classes:

class DCCmd :
    public DCMessage

class DCReply :
    public DCMessage

Both are protocol messages that are sent and received both ways.

Now in the protocol implementation I'd need to make a message queue, but with DCMessage being abstract it won't let me do something like this:

class DCMsgQueue{
private:
    vector<DCMessage> queue;
public:
    DCMsgQueue(void);
    ~DCMsgQueue(void);

    bool isEmpty();
    void add(DCMessage &msg);
    bool deleteById(unsigned short seqNum);
    bool getById(unsigned short seqNum, DCMessage &msg);
};

The problem is that, as the compiler puts it, "DCMessage cannot be instantiated", since it has a pure abstract method:

virtual BYTE *getParams()=0;

Removing the =0 and putting empty curly braces in DCMessage.cpp fixes the problem, but it is just a hack.

The other solution is that I should make two DCMsgQueues: DCCmdQueue and DCReplyQueue, but this is just duplicated code for something trivial. Any ideas? =)

like image 358
Omer Sabic Avatar asked Nov 28 '22 12:11

Omer Sabic


1 Answers

You cannot instantiate the object because it is abstract as you said. You can however hold a vector of pointers to the DCMessage class which will work, you just need to add the memory address and not the object when pushing it on to the list.

vector<DCMessage*> queue;

DCCmd* commandObject = new DCCmd(...params...);
queue.push_back(commandObject);

BYTE* params = queue[0]->getParams();
like image 147
Ryall Avatar answered Dec 04 '22 17:12

Ryall