This is more a question of ownership.
One class/function should be the clear owner of this object (or group of objects). If the object is needed in other classes/functions, then the owner should pass it to those functions as needed.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void func1(MyClass& a) { /*...*/ } // some functions that use a MyClass
void func2(MyClass& a) { /*...*/ }
int main()
{
// here, main() is the owner of this object:
MyClass obj;
// but we want other functions to use it:
func1(obj); // so we pass it to them
func2(obj);
}
|
The owner should be the one at the "top" of the access pyramid. When the owner is finished using the object,
everyone is finished using the object. Here, main is the clear owner.
To make it easier... generally the owner should be the one creating and maintaining the object. I'm doing that in the above example -- main() is the owner of 'obj', so main() is creating it.
What it sounds like you're doing is you're creating it in another function, then you want to pass ownership to someone else. I try to avoid passing ownership as it leads to very confusing code, bugs, and other problems -- but all of that can be minimized if done properly.
In your case, I would have a function return the object from it, but keep main as the owner:
1 2 3 4 5 6 7 8 9 10 11 12
|
MyClass MakeAnObject()
{
MyClass stuff;
stuff.DoThings(); // make some stuff
return stuff; // and return it
}
int main()
{
MyClass obj = MakeAnObject(); // get the object from MakeAnObject
}
|
Here, main() is still the owner, even though you arguably created the object in MakeAnObject.
For Groups of objects, it the same idea. Someone must be the clear owner of the group. As rocketboy suggested, this can be easily accomplished by using
std::vector<MyClass>
.