Archived

This topic is now archived and is closed to further replies.

dynamic objects in c++

This topic is 5514 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am going to have objects in my program that are defined by a class. One problem is that I want to be able to create more objects while the program is running. I also need to perform tasks on each object. Can anyone help me out or point me to some tutorials on creating and managing objects while running? Thanks!

Share this post


Link to post
Share on other sites
Look into dynamic memory allocation: Pointers, dynamic arrays, linked lists and so forth; keywords new and delete ... If you already know how to handle this sort of thing, it''s no different with objects than with primitive data types.

Share this post


Link to post
Share on other sites
hrmm. I see what you are saying, but how would I go through a list of dynamic objects (all derived from the same class) and check/modify each one?

What I am trying to do is create 3D objects from a class. Once an object is created I define its verticies. Then I want to be able to check If it has collided with any other objects.

Share this post


Link to post
Share on other sites
How much experience do you have with c++ ?

What you're asking is basic to any programming language really.

[edited by - daerid on November 5, 2002 6:13:20 PM]

Share this post


Link to post
Share on other sites
I have good experience, but I was wondering if there was a better, more advanced way then with just allocating memory for a larger array every time I want to add an element. (other languages are more array friendly with dynamically resizing them, so I just wondered if there was a class specific way of doing what I wanted to do.)

[edited by - shrooboo on November 5, 2002 10:06:46 PM]

Share this post


Link to post
Share on other sites
Well, arrays, by their very nature, are slow and cumbersome to resize (STL vectors are, as I understand, pretty much as good as they come, but I doubt even those are blazingly fast when they have to grow); if that concerns you (and especially if you don''t need random access), just use a linked list or some other, more appropriate data structure.

If you truly have "good experience" with C++, whipping up a linked list class should be a snap. (If, for some reason, you don''t want to use std::list ...)

Share this post


Link to post
Share on other sites
I could use linked lists, but then I would need a unique name for each object I create. That would require the equivalent of Javacript''s eval() (I think thats the one) function, where It takes a string and converts it to the name of a variable or whatever.

Ill look into std:list

Share this post


Link to post
Share on other sites
Like Oluseyi said, you don''t need a specific name or identifying property for each element in order to store and manipulate them. On the downside, however, all you have is a bunch of ambiguous objects that are all of the same type, and unless you do have some sort of identification mechanism, you won''t know how to work with the first item or the fiftieth item, assuming each item is supposed to be unique from every other item and be manipulated seperatly. An example of this would be a database program (a simple one at that), where all your records are stored in a list. If the user wishes to change the age of "Robert Smith" to "27," then you need to able to identify each record, in this case by name. An example of a usage that wouldn''t necessarily require identification is a list of particles for a particle engine. Each one in and off itself in unimportant - you simply add each particle with specific properties, and the sytem automates the behavior by calling the same Process function on all of them. You don''t necessarily need to distinguish between particle 45 and particle 874.

Share this post


Link to post
Share on other sites
zipster: your example doesn''t make sense. for one thing it''s unlikely you would specifically want to change someone''s age. if you did want to then it would be because you knew what their birthdate was and that the age value hadn''t been updated since their last birthday. the kind of process you would use to determine whether they needed updating probably would mean...
quote:
...the sytem automates the behavior by calling the same Process function on all of them


but you are right in that it''s tempting to have everything derived from one base class and put in one container. then you can''t do much useful work with them because you have to determine what they are before using them.

i think it''s better to have seperate containers which hold poniters to objects according to the useful interface, ie the one you will use automatically on all the objects in the container.

in the past i''ve created objects, put them straight into a container and later deleted them from that container. that''s fine in terms of general memory management. but i haven''t gone the next stage of also putting a pointer to that object into a useful container. i ended up having lots of casts, which, as i indicate, could be avoided.

Share this post


Link to post
Share on other sites
quote:
Original post by petewood
zipster: your example doesn''t make sense. for one thing it''s unlikely you would specifically want to change someone''s age. if you did want to then it would be because you knew what their birthdate was and that the age value hadn''t been updated since their last birthday...

Nit. Substitute for "age" "social security number" or "position".

quote:
but you are right in that it''s tempting to have everything derived from one base class and put in one container. then you can''t do much useful work with them because you have to determine what they are before using them.

Nobody said anything about deriving from a base object. The problem (see posts by thread starter) was dynamic allocation of objects, and creation of a container to store them. Since shrooboo mentions arrays, it is logical to assume the objects are all of the same type.

quote:
i think it''s better to have seperate containers which hold pointers to objects according to the useful interface, ie the one you will use automatically on all the objects in the container.

Explain this in greater detail. I prefer to aggregate heterogenous objects into collections, and store homogenous objects in sequential containers.

Share this post


Link to post
Share on other sites
maybe it is nit picking but if i can substitute 'social security number' for 'age' then why couldn't zipster?

actually where i'm from your social security number will never change either (c: but i take your point.

dynamic allocation of objects to my mind means pointers. if you need to resize the array (vector, map) then copying pointers is going to be more efficient and won't have the (possible) side effects of copying objects.

if you store an array of pointers then the temptation is to store an array of base class pointers. that was my train of thought.

collections and sequential containers - std::vector is a collection and a sequential container as well. do you have a special definition of the term collection?

i'm feeling a bit on the defensive side so your final request 'explain this in greater detail' makes me think you want to set me up to knock me down.

anyway, i've worked on professional projects where there will be a base class, say Results and then derived classes GreenResults, SadResults, LonelyResults, BlueResults which have lots of extra functionality. it doesn't really make sense to put them in a container of Results pointers. they have to be cast to the correct result before being used. there is a design problem.

this is a solution which introduces more problems than it solves.

edit: changed list to map

[edited by - petewood on November 6, 2002 4:54:26 AM]

Share this post


Link to post
Share on other sites
Hi there,

I''m not sure if this is any help to you but I suggest you use
the STL "MAP".

Even if you use vectors n lists n whatever, you will have
one of your basic problems. How do you find your object ?
Ok, I you take your time u''ll come up with something no doubt
but save urself the sweat and implement a map.

The map offers you a search algorithm to find your information (DATA)within by a KEY. Since it''s a template the KEY can be anything. An int, a char, or a string for example.

So if your class is called, for example, "CPolygon", then
your map would look like

map < DWORD , CPloygon* > PolygonStorage;

So if you want to save the pointer of an object you created,
u put it in with (lets say it has an Index of 122):

Polygon[122] = pPolygon; (which is a pointer to an existing object)


Works the same way backwards:

CPolygon pPolygon = Polygon[122]; (there it is)

Now there is something that you should try if you don''t like it
to have the map just hanging around in your code.

static map < DWORD , CPloygon* > PolygonStorage;

U make the whole thing static within the class and thus it
is accessible by the class itself and still detached from
the objects.

With a line in one of your constructors, lets say:

CPolygon::CPolygon(DWORD ID)
{
CPolygon:olygonStorage[ID] = this;

// Object ID variable declared in the header
PolygonID = ID;
}

Already all the work is done and all within the class.
And if you''re very lazy, then you let the destructor do
the cleaning up afterwards.

CPolygon::~CPolygon()
{
CPolygon:olygonStorage.erase(PolygonID);
}


Maybe it''s worth a try.

Have fun



Lorenz

Share this post


Link to post
Share on other sites
quote:
Original post by petewood
maybe it is nit picking but if i can substitute ''social security number'' for ''age'' then why couldn''t zipster?

Because he doesn''t have to?

quote:
dynamic allocation of objects to my mind means pointers. if you need to resize the array (vector, map) then copying pointers is going to be more efficient and won''t have the (possible) side effects of copying objects.

Then you lose the benefits of structures like std::vector and std::map - you''re now forced to manage the data pointed to by the sequence of pointers manually. Efficient resizing schemes can make your efficiency concerns a moot point - and that is assuming they''re not already moot (ie, profiling has determined this to be the bottleneck). Premature optimization...

quote:
if you store an array of pointers then the temptation is to store an array of base class pointers. that was my train of thought.

I''ve never thought it smart to store an array of pointers. It''s done, I know, but I''ve never really had the need. And I did, I''d use some form of smart pointer.

Yes, I know about polymorphic dispatch requiring pointers and all that; in many cases I find I can cheat using generics and obtain "compile-time polymorphism" for free.

quote:
collections and sequential containers - std::vector is a collection and a sequential container as well. do you have a special definition of the term collection?

Collections, as used in context here (it''s not an "official" definition), refer to data structures which are comprised of a heterogenous mix of objects. They don''t provide iteration or any other sequential operations (since the data is neither a sequence nor even of the same type). Classic examples include most uses of structs and classes in C and C++.

quote:
i''m feeling a bit on the defensive side so your final request ''explain this in greater detail'' makes me think you want to set me up to knock me down.

Not in the least. I''m genuinely curious.

quote:
anyway, i''ve worked on professional projects where there will be a base class, say Results and then derived classes GreenResults, SadResults, LonelyResults, BlueResults which have lots of extra functionality. it doesn''t really make sense to put them in a container of Results pointers. they have to be cast to the correct result before being used. there is a design problem.

Well what solution did you come up with? Were there any constraints on use, such as all Results-derived classes needed to be in one sequence, or could they be separate?

Share this post


Link to post
Share on other sites
i think i see what you're talking about.

a local object is declared and passed into a container which uses the copy constructor or assignment operator. there is no need for memory management; the container looks after the memory. this works for homogeneous types.

i'm talking about objects that are part of a hierarchy and hence heterogeneous.

if you use a smart pointer you need to be careful as there are ownership issues. using algorithms on the container could lead to the object being deleted. stl is designed not to work with auto_ptr. gotw article

'a collection' - i took to be equivalent to 'a container of alike objects, such as list<int>, vector<Results*> etc'. your definition is more like 'an object which agregates unrelated objects'. it would help if we were speaking the same language (c:
quote:
Yes, I know about polymorphic dispatch requiring pointers and all that; in many cases I find I can cheat using generics and obtain "compile-time polymorphism" for free.

could you give me an example - i've read modern c++ design by the way.
quote:
Well what solution did you come up with? Were there any constraints on use, such as all Results-derived classes needed to be in one sequence, or could they be separate?

unfortunately it's still in there. the design issues are so big that it never got fixed. 'if it ain't broke...'

[edited by - petewood on November 6, 2002 8:00:05 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by Oluseyi
I''ve never thought it smart to store an array of pointers.

Why not?
quote:

Yes, I know about polymorphic dispatch requiring pointers and all that; in many cases I find I can cheat using generics and obtain "compile-time polymorphism" for free.

Compile-time polymorphism is not a substitute for run-time polymorphism - it''s just to do with when you have the necessary information to despatch the call. If you don''t have the information until runtime, then you can only choose from runtime despatch mechanisms and containers of pointers becomes your only choice. This is a very common thing to want to do.
quote:

Collections, as used in context here (it''s not an "official" definition), refer to data structures which are comprised of a heterogenous mix of objects. [...] Classic examples include most uses of structs and classes in C and C++.

It would make it clearer if you called this concept an "aggregate" or a "tuple". You can''t use a commonly understood term such as "collection" (a group of things) and expect people to know what you mean if you are using it in a manner that departs from the commonly understood meaning.
quote:

Explain this in greater detail. I prefer to aggregate heterogenous objects into collections, and store homogenous objects in sequential containers.

I believe what petewood is referring to is that, whenever you store a number of objects in a container, you choose how to group the objects together according to the interface they present. The reason for that is if there is an ontological relationship between the objects making you want to group them together, then there must be a requirement in your program leading to that. Since your program must want to view these objects as a logical collection and, since your program only views objects via their interface, it must be the semantics of the interface that leads you down this path. If a group of objects have completely different interfaces, and are therefore different "things", then why would you want to group them together?

Share this post


Link to post
Share on other sites
Just as a sideline, considering the basic nature of Shrooboos original question, don't you think we're beginning to drown in jargon a bit here? I am impressed by the use of "Ontological" though, I've never seen it used outside a philosophy text

Anyhows, there are situations where you may want to group unrelated objects into a single collection (vertex, linked list, array or whatever). The example that springs to mind is collision detection:

The players space ship can collide with the following types of objects:

a) Bullets, missiles from enemies
b) Enemy ships
c) Scenery objects

Despite the fact that all of these groups are ontologically unrelated, we can see an epistomological association between them (e.g. we know that each one may be collided with). This can be handled, via the evil that is known as multiple inheritance, by forcing all of the objects to inherit from a common collidable object interface. A spatial partitioning algorithm can then aggregate all of the bullets, enemies and scenery pieces that are nearby the player's ship into a single collection of collidable objects to allow all the ship collision detection to be done in one rather than three seperate batches.



[edited by - bligblug on November 6, 2002 8:46:44 AM]

[edited by - bligblug on November 6, 2002 9:07:22 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by bligblug
Just as a sideline, considering the basic nature of Shrooboos original question, don't you think we're beginning to drown in jargon a bit here?

Perhaps, but I was responding to a tangential issue, not the original question.
quote:

I am impressed though by the use of "Ontological" though, I've never seen it used outside a philosophy text

To put it another way, I'm trying to say that there has to be something about the nature of the objects that makes you want to group them together. If there is nothing of the kind, then how do you reach the conclusion that those objects should be grouped together?
quote:

Anyhows, there are situations where you may want to group unrelated objects into a single collection (vertex, linked list, array or whatever).

I disagree, but the reason I disagree hangs on the meaning of "unrelated". I'm contesting that there *has to* be some relationship for you to want to group them together, unless you're in the habit of grouping things randomly, in which case you're probably quite mad.
quote:

The example that springs to mind is collision detection:

I propose that any objects within a game that can collide with one another are related at least by the facts that they are all game objects (either static or mobile); are all contained within the same space; and that they can collide with one another. They *must* have some common and knowable interface representing each of the contexts in which they are to act.
quote:

Despite the fact that all of these groups are ontologically unrelated, we can see an epistomological association between them (e.g. we know that each one may be collided with).

I think its too easy to play with the semantics of those two words, so I'll put it in another way...

Basically, I'm saying that if you want to group things together, that is because you perceive a commonality about those objects that makes you want to treat them in the same way as one another in a particular context. The general means of modelling this commonality in a program is to implement an interface representing the semantics of how you treat them in that context, and you group them together according to that interface. That, I believe, is what petewood was alluding to. Furthermore, if you find yourself grouping objects where there is no common interface, it is not because they are unrelated, but because they do not correctly model their intended usage.

Your example of collision detection actually illustrates the point: that you want to view the objects as being able to collide with one or another for the context of collision detection.

The term "heterogeneous collection", although we all use it, is not a well-defined one. It's not even something that C++ will allow you to express without vile contortions of the language.

[edited by - SabreMan on November 6, 2002 9:26:30 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by SabreMan
Why not [store an array of pointers]?

As much as possible, one tries to minimize data memory management responsibility. Thus the creation of containers that dynamically resize and wrappers that deallocate the wrapped memory (usually via a pointer as an implementation detail). I only store pointers directly when I have no other reasonable option.

quote:
Compile-time polymorphism is not a substitute for run-time polymorphism - it''s just to do with when you have the necessary information to despatch the call. If you don''t have the information until runtime, then you can only choose from runtime despatch mechanisms and containers of pointers becomes your only choice. This is a very common thing to want to do.

You''re right. You''re absolutely right. The thing is that many people use traditional inheritance mechanisms to obtain compile-time polymorphism. When runtime polymorphism is the behavior desired, there are no alternatives to runtime dispatch methods.

quote:
It would make it clearer if you called this concept an "aggregate" or a "tuple". You can''t use a commonly understood term such as "collection" (a group of things) and expect people to know what you mean if you are using it in a manner that departs from the commonly understood meaning.

Sorry, I couldn''t find the appropriate word (tuple) at the time. I did try to use aggregate as a hint (should have been more explicit).

quote:
I believe what petewood is referring to is that, whenever you store a number of objects in a container, you choose how to group the objects together according to the interface they present. The reason for that is if there is an ontological relationship between the objects making you want to group them together, then there must be a requirement in your program leading to that. Since your program must want to view these objects as a logical collection and, since your program only views objects via their interface, it must be the semantics of the interface that leads you down this path. If a group of objects have completely different interfaces, and are therefore different "things", then why would you want to group them together?

I actually think petewood refers to the inverse, as your opinion mirrors mine, in much greater detail and clarity. He mentioned the common, though inappropriate technique of creating relationships between unrelated types by deriving them from some base type to which I responded that the apparent problem domain indicated that the objects being aggregated here were all of the same type.

Share this post


Link to post
Share on other sites
quote:
Original post by Oluseyi
[quote]Original post by bligblug
Just as a sideline, considering the basic nature of Shrooboos original question, don''t you think we''re beginning to drown in jargon a bit here?

Topic drift can often lead to unexpected knowledge acquisition. You can''t fight it

Too true, here was me thinking homogenous was a type of milk

quote:
Original post by SabreMan
Basically, I''m saying that if you want to group things together, that is because you perceive a commonality about those objects that makes you want to treat them in the same way as one another in a particular context. The general means of modelling this commonality in a program is to implement an interface representing the semantics of how you treat them in that context, and you group them together according to that interface. That, I believe, is what petewood was alluding to. Furthermore, if you find yourself grouping objects where there is no common interface, it is not because they are unrelated, but because they do not correctly model their intended usage.



Yup I agree with you. I think the point I was trying to make was that just that because an object exists in one collection of related objects, doesn''t mean that it can''t also exist in a seperate collection of objects that are related in an entirely different way.

Things to remember: Never use the words ontological and epistomological in the same sentance, you will probably end up confusing yourself even more than you confuse other people

Share this post


Link to post
Share on other sites
oluseyi:

i agree totally with sabreman as i often do (he''s my knight(lore) in shining armour).

and if you agree with him, how come we disagree? i guess he''s better at expressing things than i am.

i do mean group by interface.

ps i always read your answers as i find your knowledge and insight really helpful. that''s why i get so jittery when you start asking me questions (c:

Share this post


Link to post
Share on other sites
thinking about it, the reason i don''t store objects like you suggest and that i do use pointers is the following.

the design of my classes would have to be first-class. by that i mean my objects would have to have copy constructors, assignment and all the other things necessary for them to be safely passed around like you can with an ''int'' or a ''complex<double>''.

so really my lack of use of your ideas, oluseyi, is laziness. and it''s generally bad programming anyway because as we know when you design a class you design a type.

thanks for your suggestions, i think i''ll try and use them when it''s appropriate. i work a lot with runtime-polymorphic hierarchies so i''ll still use pointers for them.

thanks again.

pete

ps i did once code something to use objects rather than pointers in a deque that had a high turnover. it meant i didn''t have to allocate/deallocate using the heap and actually speeded up the code by about 10 times.

Share this post


Link to post
Share on other sites
quote:
Original post by Oluseyi
Thus the creation of containers that dynamically resize and wrappers that deallocate the wrapped memory (usually via a pointer as an implementation detail).

Ah, so you don''t object to storing containers of *smart* pointers, then? Sounds like we''re in agreement.
quote:
Original post by bligblug
Things to remember: Never use the words ontological and epistomological in the same sentance, you will probably end up confusing yourself even more than you confuse other people

LOL! Well, I started thinking about how those words relate to what I was saying, and they are both valid, but which one is correct at which time depends on a subtle variation in how you view things. If you were a stock forum arguer, you''d be using that to try and pin me down on something entirely different and end up demonstrating how I''d claimed David Hasselhoff is a great singer.
quote:
Original post by petewood
thinking about it, the reason i don''t store objects like you suggest and that i do use pointers is the following.

the design of my classes would have to be first-class.

You mean value types? Yep, a prime reason for using handle classes.

Share this post


Link to post
Share on other sites
And...

quote:
Original post by bligblug
Yup I agree with you. I think the point I was trying to make was that just that because an object exists in one collection of related objects, doesn''t mean that it can''t also exist in a seperate collection of objects that are related in an entirely different way.

Well actually, an object can''t be in two places at once, which is yet another reason for using pointers. Or, rather, handle classes. But yes, I know what you mean, and I agree. It''s often desirable to have multiple "views" of the same object.

Share this post


Link to post
Share on other sites