R
Ramon F Herrera
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?
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
{
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);
return 0;
}
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?
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
{
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);
return 0;
}