Lately I have wondered how should a composition be implemented when it comes to adding objects within an object. Here's a simple piece of code to demonstrate the use:
1 2 3
X x;
Y y;
x.insert(y);
As you can see, object y will be inserted into object x. But how? This is what I'm wondering. Here's the implementation of class X:
Now, is this a good idea? I've heard that the use of dynamic memory allocation should be avoided whenever possible. Prefer stack, right? Well, if that's the case here, there might some kind of danger when it comes to using this class. Can you guess what the problem is? It's the problem that appears after the object y falls out scope:
1 2 3 4 5
X x;
Y y;
x.insert(y);
// Y goes out scope, x points to a non-existing object if I'd use stack instead of heap.
Thanks, coder777. I forgot to specify that object x is supposed to contain object y by reference. That way I can modify object y and see the effects also in object x. Here's an example:
1 2 3 4 5 6
Character bob;
Health health;
bob.insert(health);
health -= 15; // Affects object "bob".