Link to home
Start Free TrialLog in
Avatar of Kaimelar
Kaimelar

asked on

Objects creating and passing objects to other objects?

I am developing a model in C++.  One of the main sections of the model consists of two objects: nodes and packets.

My packet objects are really just glorified structures storing storing integer data.

The node class includes several public methods to manipulate it, as well as a private STL list member to store packets -- a buffer, if you will.  Nodes can do several things.  The two most important are: 1) storing packets given to it and 2) moving packets from itself to a given node.  They do this using the following methods:

void add_packet(Packet p);
void move_packet(Node destination);

The add_packet method simply adds p to the end of the STL list contained in the node.  It's the move_packet method that is giving me problems.  Originally, I thought I could simply make a copy of packet I wanted to move, add it to the destination node (using add_packet, of course) and then delete the node from the starting list (the list contained in the object handling the message).  However, this did not produce the desired results.

Looking into the bug I found that while I'm in the move_packet method, everything is fine -- the destination node contains what it's supposed to and at the proper time.  However, as soon as I exit the method, the packet object disappears.

I've fooled around with several ways of getting around this, all to no avail.  What am I missing?  IOW, How do I move object A from object 1 to object 2?
Avatar of jhance
jhance

Is there a reason why you've asked this question 3 times?
OK, make that 4 TIMES!!!
Please delete the DUPLICATES and get your points back.
Avatar of Kaimelar

ASKER

My apologizes for the duplicated questions -- refreshing my browser caused the question to be submitted multiple times.
ASKER CERTIFIED SOLUTION
Avatar of JackThornton
JackThornton

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
JackThornton is right.
I have 2 guesses regarding your packet class:
1. In the class there are data members that are pointers.
2. you did not implement copy constructor.

When you pass a copy of the object to the method, a shallow copy is been perform by the default copy constructor, i.e. only the VALUE of the pointer is been copy instead of the CONTENT of the pointed address.
So, you can do as JackThornton suggested, which is the right thing to do in most cases, or implement a copy constructor for the class.

--EC--
JackThornton hit the nail on the head -- I'd been so obsessed with the way the method was working I didn't even think about the parameters I was passing into it.  Thanks to everyone who looked at this problem.