Setting pointer in function

Hello,

I want to do the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class A {
  
private:
  B* myPointer;

public:
  void someMethod() {
    B b = B();
    b.setPointer(myPointer);
  }

};

class B {
  
public:
  void setPointer(B* pointer) {
    pointer = this; 
    // the pointer in A should now be set but isnt
  }

};

int main(int argc, char* argv) {
  A a = A();
  a.someMethod();
}
  


Why does myPointer not get set? I want it pointing to b. It's important that myPointer gets set in a function of class A.

Can someone help me?
At line 17, you're passing pointer by value. Any changes to pointer won't be reflected in the caller. It also doesn't make much sense since the caller could accomplish the same thing by simply taking the address of b without needing to call setpointer.

Lines 8 and 25 don't make sense. It looks like you're trying to set b to the default constructor of B. That's not necessary, since B's default constructor will get called anyway.

It's important that myPointer gets set in a function of class A

I don't see anything that attempts to do that.
I read your other thread, and I still don't understand what you're trying to do.

A has no default constructor, so A::mypointer is uninitialized.


I've changed it to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class A {
  
private:
  B* myPointer;

public:
  void someMethod() {
    B b;
    b.setPointer(&myPointer);
  }

};

class B {
  
public:
  void setPointer(B** pointer) {
    *pointer = this; 
  }

};

int main(int argc, char* argv) {
  A a;
  a.someMethod();
}

and now it works. mypointer gets set corretly by calling setPointer. If you could confirm that that's correct now I'd be grateful!
Last edited on
That doesn't appear to accomplish anything.

At line 8, b is local to someMethod. It promptly goes out of scope at line 10.

I realize you've simplified this and that there may be other code that is not shown.
I can only comment on what I see.

Topic archived. No new replies allowed.