Hi,
I'm having a bit of trouble deciding on which way I should pass objects to other objects. There appears to be 3 main ways of doing it: pass by reference, pass by value and pass by pointer. I understand how each of these works but I don't know when to use each of them. For example, take this bit of code:
Code:
#include "MainClass.h"
#include "OtherClass.h"
MainClass mClass;
void init() {
OtherClass oc;
// do stuff with oc
mClass.setOtherClassUsingPassByValue(oc);
}
int main() {
init();
mClass.doStuffWithOtherClass();
return 0;
}
This is really simple, but am I right in saying it wouldn't be a good design if OtherClass was fairly big (memory wise)?
Another way to do it would be to use pointers (same code except init method):
Code:
void init() {
OtherClass* oc = new OtherClass();
// do stuff with oc
mClass.setOtherClassUsingPassByPointer(oc); // mClass takes ownership of oc
}
This is also simple, but I've read in numerous places that you should avoid pointers wherever possible and use references, instead of pointers in methods of objects.
So this is a reference way:
Code:
void init() {
OtherClass oc;
// do stuff with oc
mClass.setOtherClassUsingReference(oc); // mClass takes ownership of oc
}
But Im not sure if this way would work as would oc delete itself when init finished? To fix that problem, I could do:
Code:
void init() {
OtherClass& oc = *new OtherClass();
// do stuff with oc
mClass.setOtherClassUsingReference(oc); // mClass takes ownership of oc
}
But that, while it would probably work, seems messy (I've never seen *new used before). So I was wondering what was the general way of solving this problem.
Also, a similar problem, how do you normally store objects inside a class (eg MainClass)? I.e as a pointer, reference or value and when is each appropriate?
Thanks!