[ACCEPTED]-In C++, how can I hold a list of an abstract class?-abstract
You cannot instantiate the object because 5 it is abstract as you said. You can however 4 hold a vector of pointers to the DCMessage 3 class which will work, you just need to 2 add the memory address and not the object 1 when pushing it on to the list.
vector<DCMessage*> queue;
DCCmd* commandObject = new DCCmd(...params...);
queue.push_back(commandObject);
BYTE* params = queue[0]->getParams();
You want a vector of DCMessage pointers:
vector<DCMessage*> messages;
messages.push_back(new DCCmd(blah));
Polymorphism 3 in C++ only works through pointers and references, and 2 you can't use references for this. So, pointers 1 it is.
If you want polymorphism, you need pointers 16 in C++, so would use a deque of pointers 15 to the abstract type ( assuming it's a FIFO 14 queue rather than a LIFO ). You then have 13 the problem of managing who owns the messages 12 in the queue.
However, C++ isn't just about 11 OO, and there are idioms in C++ for writing 10 objects to streams; if the message queue 9 just forwards them to a tcp port or has 8 a behaviour similar to , you might want 7 to use those idioms and copy the data rather 6 than storing a reference to the object. If 5 you're implementing techniques to marshall 4 your message objects to and from binary 3 anyway, you might end up saving yourself 2 some bother if your queue is just a buffered 1 stream.
(Voted Kelix up, but I think this needs 12 more elaboration)
What you are looking to 11 do is create a vector of elements that can 10 be of any object derived from your abstract 9 class, right? When you say vector <DCMessage>
, you are instead 8 asking for a vector of elements of class 7 DCMessage. You can't have them, as that 6 is an abstract class.
If you instead ask 5 for vector <DCMessage *>
, then you can supply pointers to objects 4 of any class derived from DCMessage, and 3 will get dynamic (runtime) dispatch to the 2 correct implementation of your abstract 1 routines when invoked at runtime.
Other answers point out that you can have 9 only pointers of abstract classes. When 8 you use that in a container like list, after 7 you remove elements, you will have to manually 6 remove their memory as well, since the container 5 operations will just work on the pointer 4 value itself and not what is being pointed 3 to.
In cpp-11 you can use wrappers like unique_ptr<some_type>
to 2 achieve your goal without dealing directly 1 with pointers:
list<unique_ptr<your_abstract_class>> someList;
someList.push_back(make_unique<your_derived_class>()); // will create new instance
someList.push_back(make_unique<your_other_derived_class>());
someList.pop_front(); // will remove the instance and automatically call its destructor
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.