| Henri Korpela (43) | |||||||
|
Hello! 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:
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:
So, is the use of heap justified here? | |||||||
|
|
|||||||
| coder777 (2375) | |||
The issue isn't stack vs heap. The issue is whether to copy the data or not. You can copy the data if it's not too much. You must not copy the data when the data contains pointer or inheritance is involved. When it comes to variable size data you do not have a choice but to use dynamic memory allocation.
Y _m_opY; you had a copy of y. So no problem[EDIT] by the way: This is a copy anyway: _m_opY = new Y(y);[/EDIT] | |||
|
Last edited on
|
|||
| Henri Korpela (43) | |||||
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:
And here's a little fix (should be correct now):
So, should I use dynamic memory allocation in this case? | |||||
|
Last edited on
|
|||||
| Athar (4379) | |||
No, you're allocating memory and you lose the pointer to it in the next line. That's a classic memory leak. Drop the first line, it's pointless.
That depends on whether "health" outlives "bob". As I see it, health should be a member of Character. | |||
|
|
|||