In a class App I pass a pointer to a function :
class App {
private:
Bob b;
Pop * p;
public:
void do() {
b.init(p)
// Use p for various stuff
}
};
class Bob {
typedef Pop P;
public:
void init(P * p) {
p = new P();
}
};
But after calling b.init(p) in App I get memory errors when I use p. What am
I doing wrong?
You pass the pointer 'p' to Bob::init() by value, not by reference.
Modifying it's value in Bob::init() only has an effect on the local
function parameter 'p', and does not modify the variable that you've
passed in. Consider a simpler example:
int x = 0;
void set_value_to_5 (int value) {
value = 5;
}
int main () {
set_value_to_5(x);
}
In this example, x is not set to 5. The modification of 'value' in
set_value_to_5() has no effect on x. Passing the parameter by
reference would result in 'x' being modified:
void set_value_to_5 (int &value) { // <-- by reference
value = 5;
}
The same goes for your pointer:
int *x = NULL;
void init_pointer (int *ptr) {
ptr = new int;
}
int main () {
init_pointer(x); // does not modify x
}
You'd want to pass the pointer by reference:
void init_pointer (int * &ptr) {
ptr = new int;
}
You may be getting confused because your syntax resembles a common
technique of using pointers to pass objects by reference, e.g.:
void set_value_to_5 (int *value) {
*value = 5;
}
However, this is not the same as what you are trying to do. The
pointer itself is passed by value. If you did this:
int x = 0;
void set_value_to_5 (int *value) {
*value = 5;
value = new int;
}
int main () {
int *ptr_to_x = &x;
set_value_to_5(ptr_to_x);
}
Then x would be set to 5, although ptr_to_x would still point to x
(and not to a new int).
HTH,
Jason