Re: Issues related to storing heterogeneous-sized objects in a vector
Ramon F Herrera wrote:
Newbie alert: I come from C programming, so I still have that frame of
mind, but I am trying to "Think in C++". In C this problem would be
solved using unions.
Hello:
Please consider the snippet below. I have some objects which are
derived (subclassed?, subtyped?) from simpler ones, in increasing
size. There is a linear hierarchy. I need to keep them all in some
sort of linked list (perhaps std::vector). I could have several
vectors, one for every different class, but I have an intuitive belief
that C++ must be able to provide a means to save all the objects in
the same vector.
Issue #1: Notice the definition of the vector. Should I use the
largest class (vector<pentagon>) to reserve space for the extreme
case? Or, should I define a vector<triangle> instead since the others
are inheritors of the triangle class?
Maybe my approach is wrong to begin with?
Yes.
TIA,
-RFH
-------------------
#include <vector>
using namespace std;
struct point
{
int x, y;
};
class triangle
{
public :
point vertex1;
point vertex2;
point vertex3;
};
class square : public triangle
This is not good. A square is not a triangle. The line above means that you
can pass a square to each function that takes a triangle as an argument.
But that will generally not make any sense.
{
public :
point vertex4;
};
class pentagon : public square
{
public :
point vertex5;
};
int main()
{
vector<triangle> piggybank;
triangle *love_affair = new triangle;
square *boxing_ring = new square;
pentagon *military = new pentagon;
military->vertex5.x = 123;
military->vertex5.y = 456;
piggybank.push_back(*military);
piggybank.push_back(*boxing_ring);
piggybank.push_back(*love_affair);
Google for "slicing". All you do is copy the triangle subobjects into the
vector.
If you need a vector whose entries are polymorphic, you should consider
vector< BaseClass * >
or (usually better)
vector< some_smart_pointer< BaseClass > >
where the smart pointer would have the right semantics (e.g., deep copy if
you want value semantics mimicking the behavior of containers most
closely).
return 0;
}
A more fundamental question is about the semantics of your objects. Are
objects of type triangle supposed to be values (i.e., different objects can
be the same triangle) or are they supposed to be entities (i.e., different
objects will always be different also their member variables might have
identical values). Containers work better with values, OOP in C++ works
better with entities. Pointers interface between values and entities (since
the address of an entity object is a value).
Best
Kai-Uwe Bux