I feel I miss some key concepts about references and pointers; I have the code like this
#include "stdio.h"
struct bar {};
class foo {
public:
foo(){
barPtr = new bar();
};
bar* barPtr;
bar*& getBarPtr() {
return barPtr;
};
};
int main() {
foo fObject;
bar* b = nullptr;
b = fObject.getBarPtr();
printf("B before updates %p\n", b);
printf("barPtr before b updates %p\n", fObject.barPtr);
b = new bar();
printf("B after updates %p\n", b);
printf("barPtr after b updates %p\n", fObject.barPtr);
return 0;
}
The output is
b before updates 0x55db559ace70
barPtr before b updates 0x55db559ace70
b after updates 0x55db559ad2a0
barPtr after b updates 0x55db559ace70
What I want to achieve is changing what barPtr points to by using b, so I make getBarPtr function returns the reference of barPtr. What I don't understand is why changing b doesn't change barPtr.