interobject communication

hi,
anybody have an idea how I can get two objects of the same class to communicate with each other. The objects are contained in a vector.

Thanks,
openSource.
Last edited on
It depends what they need to tell one another, but one way would be to pass a pointer/reference to one, to one of the methods, and have that method call the appropriate method of the passed object.
I have tons of ideas; what do you really want to do so that we can narrow it down a bit?
basically I want an object to copy certain attributes from another object that has a minimum value for a certain function. I need the object to determine which other objects in the vector minimize the function and then copy the values from them.

Alternatively, my object can notify the class that contains the vector to get it the values. This would be better from the design perspective. I don't know any way an object can call its container object either so a solution to any of these problems would help.
So, you have a class containing a container of Widgets.
You want to update the Widgets with a set of values from a specific Widget (the one that is minimal regarding to a certain function).

I assume this shall happen if a certain function of your class is called?

Then why not simply:
a) determine the minimal Widget (use something like the "min" method for vectors)
b) iterate over the Widgets (maybe skipping the minimal Widget) and
c) either call a method on each Widget like "copy_attributes_from(const Widget& other)" with the minimal Widget as the argument
or
c') or set the attributes in the iteration step manually.

This way the Widgets are not too closely tied to the class.
This is what I originally thought. But the thing is I'm actually using this in a computer game with the objects in the vector being non-player characters. This means that the objects decide when to call a function: its event driven.

If I used the method above then I'll have to check in each cycle of the game loop even when there is no activity by any of the characters, unnecessarily slowing execution.

something more along the lines of event driven programming would be more helpful.

Make all objects being added to the vector have a pointer to the object that has the instance of that vector. This is preferably done like this:
1
2
3
4
void NPC::addToVector(Container *ctn){
    ctn->addToVector(this);
    this->container=ctn;
}

Each time an object is modified, have it call a function in the container class that adds a pointer to that object, to a member queue. Now all the container needs to do is wait until !this->queue.empty().

If you're using multithreading, make sure you wrap things with mutual exclusions.
Last edited on
Topic archived. No new replies allowed.