Updating a pointer

Hello,

I have the following:
1
2
3
4
5
6
7
8
9
10
class X;

class A {
  X* ptr;
  // ...
};

class B {
  // ...
};


I need some method to update ptr in class B. I thought of saveing a X** in B and updating ptr through that but it didnt work.

Background:
I have a vector of objects in class B and for each of that objects a pointer in class A. When B updates the vector (changing the pointers) I want to automatically the pointer in A with B knowing the minimum amount about A.
Last edited on
Let me see if I'm understanding you correctly. You have two classes, each with a pointer to an array of X's.
1
2
3
4
class X;

class A{ X* ptr; };
class B{ X* ptr; };


And the pointers in A and B are likely to point to the same array, or part of the same array.

And your goal is, if a pointer in a B object is assigned a new memory address, to be able to reflect the change in the A object as well?

Well, there are several options:
-Use std::shared_ptr (or boost's). This ensures that the memory will be cleaned up at some point. Then you can change the pointers at A and B objects separately.
-Use X** as you mentioned, so the two objects will always use the same pointer.
-Create a function in both A and B that lets you place requests to change the pointers, then allow that function to do the clean up. Of course, using a function means you will probably need a second function to pass the object of the other class as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void A::change_ptr(X* newptr){
   delete[] this->ptr;
   this->ptr = newptr;
}
void A::change_ptr(X* newptr, B& twin){
   this->ptr = newptr;
   twin.change_ptr(newptr);
}
void B::change_ptr(X* newptr){
   delete[] this->ptr;
   this->ptr = newptr;
}
void B::change_ptr(X* newptr, A& twin){
   this->ptr = newptr;
   twin.change_ptr(newptr);
}
Are A and B releated? Does it make sense for them to share a base class that contains the pointer to X?

1
2
3
4
5
6
7
8
9
10
11
class C  // shared base class
{  
protected:
    X * ptr;
};

class A : public C 
{}

class B : public C
{}


Now code in A or B can modify the pointer to X in the base class.
I dont get this working:
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
class A {

private:
  A** writebackPtr;

public:
  void setPointer(A* pointer) {
    writebackPtr = &pointer;
    pointer = this;
  }

};

class B {

private:
  A* myPointer;

public:
  void someMethod() {
    A a = A();
    a.setPointer(myPointer);
    // writebackPointer is set but
    // myPointer == 0 .... why?
  }

};


Use of all this should be that e.g. when copying A I can automatically set myPointer to the new Object without A knowing anything of B
Topic archived. No new replies allowed.