473,396 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Issues related to storing heterogeneous-sized objects in a vector


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<triangleinstead 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;
}

Jun 27 '08 #1
3 1659
On Jun 12, 10:59 pm, Ramon F Herrera <ra...@conexus.netwrote:
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<triangleinstead since the others
are inheritors of the triangle class?

Perhaps there is a way to specify all possible classes that will be
welcome in the vector? This would be my guessed syntax:

vector<triangle|square|pentagonuniversal_container ;

Could this be a job for templates (which I barely understand)?

-RFH

Jun 27 '08 #2
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<triangleinstead 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
Jun 27 '08 #3
On Jun 12, 10:59 pm, Ramon F Herrera <ra...@conexus.netwrote:
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.
You certainly can, assuming you design a hierarchy that supports a
base type.
Think 'Shapes'
>
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<triangleinstead since the others
are inheritors of the triangle class?

Maybe my approach is wrong to begin with?

TIA,

-RFH
Consider the following, lets forget the coordinate system for now

#include <iostream>
#include <vector>

class Shape { };
class Triangle : public Shape { };
class Rectangle : public Shape { };
class Circle : public Shape { };

int main()
{
std::vector< Shape* shapes;

Triangle tri;
Rectangle rect;
Circle circ;

shapes.push_back(&tri);
shapes.push_back(&rect);
shapes.push_back(&circ);

std::cout << "vector shapes has ";
std::cout << shapes.size() << " elements\n";
}

>
-------------------

#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;

}
I'ld suggest choosing a smart_pointer instead of new.
You would end up with something like the following (using
boost::shared_ptr in this case)

#include <iostream>
#include <vector>
#include "boost/smart_ptr.hpp"

class Shape { };

class Triangle : public Shape
{
public:
~Triangle(){ std::cout << "~Triangle\n"; }
};

class Rectangle : public Shape
{
public:
~Rectangle(){ std::cout << "~Rectangle\n"; }
};

class Circle : public Shape
{
public:
~Circle(){ std::cout << "~Circle\n"; }
};

int main()
{
std::vector< boost::shared_ptr<Shape shapes;

// Triangle tri;
// Rectangle rect;
// Circle circ;

shapes.push_back(boost::shared_ptr<Shape>(new Triangle));
shapes.push_back(boost::shared_ptr<Shape>(new Rectangle));
shapes.push_back(boost::shared_ptr<Shape>(new Circle));

std::cout << "vector shapes has ";
std::cout << shapes.size() << " elements\n";
}

/*
vector shapes has 3 elements
~Triangle
~Rectangle
~Circle
*/

The above uses default constructors only, if parametized ctors are
supplied, the concept remains the same.
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Cpt. Zeep | last post by:
Although this is not strictly PHP related question, i presume lots of you are good in MySql so maybe you could help me. I am making sort of yellowpages application and have following issue: I...
28
by: grahamd | last post by:
Who are the appropriate people to report security problems to in respect of a module included with the Python distribution? I don't feel it appropriate to be reporting it on general mailing lists.
1
by: kj | last post by:
The main rationale I have seen for namespace support in XML is to enable the peaceful coexistence of XML fragments from various sources within the same ("heterogeneous") XML document without their...
17
by: tuvok | last post by:
How can objects of different types be stored in a collection? For example: struct S1 { /*...*/ }; struct S2 { /*...*/ }; struct Sn { /*...*/ }; template<typename T> class X { public:
4
by: Robin Tucker | last post by:
Hi, I'm currently implementing a database with a tree structure in a table. The nodes in the tree are stored as records with a column called "Parent". The root of the tree has a "NULL" parent....
7
by: Greg Collins [MVP] | last post by:
Hi, I couldn't find what I was looking for by searching the newsgroup, but perhaps these have already been discussed somewhere. This is a bit long with a lot of interrelated questions. What I've...
10
by: Robert | last post by:
I have an app that was originally 1.1, now migrated to 2.0 and have run into some sporadic viewstate errors...usually saying the viewstate is invalid, eventvalidation failed or mac error. My web...
1
by: Bob Rock | last post by:
Hello, I'm new to ASP.NET and I've been looking into the topic of dynamically loading (typically accomplished with a LoadControl followed by a MyControl.Controls.Add()) both user controls and...
62
by: Tony Ciconte | last post by:
I have a rather complex commercial Acc2003 application (tab controls, 50K+ lines of VBA code, etc.) that will not run well at all on Windows Vista Ultimate. I have seen posts indicating that...
2
by: RSH | last post by:
I have a situation where I have a page called "HiddenFrame.aspx" that contains a public property exposing the value of a textbox called "TextBox1" that is in a hiddenframe. Loaded in the main...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.