Reputation: 9262
Based on the question Using array of pointers as parameter to method I would like to ask what possible ways are available when someone want to create a structure of references to a class which is abstract. Afterwards it is filled with different Objects whose class is apparently derived from the same base. This structure must also be “transfered” inside functions of diverse classes being passed as argument.
I followed the strategy presented in the linked question (which of course is flawed) because I could not declare an array of Objects of an abstract class. However this is attainable through array of pointers. Can this be done with a vector without using pointers like:
vector<Square> allSquares;
? Do the references in that case hold their initial address wherever, if the vector itself is passed with reference (&allSquares)?
Upvotes: 1
Views: 1167
Reputation:
You cannot pass or hold abstract objects by value, you get slicing, mentioned here. Basically, you lose all of your data. You have to store them by reference, by pointer, or by a smart pointer(shared_ptr).
The simplest thing by far would be to manage all of your abstract objects as shared_ptrs. This way you do not have to deal with the complex problem of lifetime. Your objects will delete themselves when they are no longer necessary.
The following is example syntax using this method.
std::vector<boost::shared_ptr<Shape> > shapes;
shapes.push_back(boost::make_shared<Rect>());
boost::shared_ptr<Shape> foo = shapes[0];
foo->draw(); //Draws the rectangle.
Upvotes: 2
Reputation: 183612
A vector<Square>
contains actual instances of Square
itself, not of any of its subclasses. (C++ only supports polymorphism via pointers, not by values.) Since Square
is an abstract class, there can be no instances of Square
itself, so a vector<Square>
is basically meaningless. You need to use vector<Square *>
.
Upvotes: 0
Reputation: 9937
Yes, it's fine to have an array of an abstract type, it's often very handy but you'll probably want to have an array of pointers, ie:
vector<Square*> allSquares;
instead of simply the objects themselves since the size of each type can vary but c++ pointers are constant in size, that is, c++ pointers on a 32-bit system are are stored as int.
Upvotes: 0