It appears that C++ does not allow this (in Java it was possible).
It is not possible in Java either since Java only has reference variables for objects.
Originally Posted by sarmadys
1- May I know what do I not understand here? We cannot refer to sub-class instances with a reference of parent class type?
You can. However, Action is not a reference (or pointer). A vector<Action> is a vector of objects where each object is of the Action class, and not of any Action subclass. Since Action is an abstract base class, you thus cannot have a vector<Action> since objects of the Action class itself cannot exist.
Originally Posted by sarmadys
2- Should I use vector of pointers instead or what?
Yes, or a vector of smart pointers, or a boost::ptr_vector<Action>.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
It is not possible in Java either since Java only has reference variables for objects.
I used to have an ArrayList<Action> and just add all sub-class instances into it and it would not object.
Originally Posted by laserlight
Yes, or a vector of smart pointers, or a boost::ptr_vector<Action>.
So by using pointers now I should use "new" and manage the dellocation myself using "delete". right? It is going to be more messy. That's why I try to use C++ automatic "garbage collection LIKE" mechanism.
I used to have an ArrayList<Action> and just add all sub-class instances into it and it would not object.
You are mistaken: you did not "add all sub-class instances into it". You added references to those instances to the ArrayList. In colloquial terminology we say "instance" in Java to also mean a reference to that instance, but technically you are storing references to the instances, not the instances themselves.
Originally Posted by sarmadys
So by using pointers now I should use "new" and manage the dellocation myself using "delete". right?
Yes, unless you are just storing pointers that point to existing objects.
Originally Posted by sarmadys
It is going to be more messy. That's why I try to use C++ automatic "garbage collection LIKE" mechanism.
Use vector of smart pointers or a boost::ptr_vector<Action>.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Use vector of smart pointers or a boost::ptr_vector<Action>.
I am sorry to take more time of you. Boost documentation for ptr_vector does not describe what is exactly the benefit of using it instead of std::vector. May I know that?
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks