I can't access/modify the member object of wrapper class by another member object of the same class.

Basically, I have a transform object and collider object inside a gameobject and I wish to access the transform of parent gameobject from inside the collider object and modify it.

struct Transform{
   //some members
};

class Collider{
  //some members
  Transform *transform;
  Collider(/*somethings*/, Transform* _transform):transform(_transform){
     //some things
  }

  //some method to check collision and update transform of gameobject
};

class GameObject{
   //some other components
   Transform transform;
   Collider collider;

   GameObject(Transform transform) : collider(/*some default values*/, &(this->transform)){
      //initializing 
   }
};

int main(){
   // some code
  
   for(int i=0; i<10<i++){
      GameObject quad(Transform(/*params*/));
      quads.push_back(quad);
   }

   // some other code
}

I tried other methods achieve this but everything except the transform will initialize to correct value. The closest I have came for correct initialization is by storing an alias of transform in collider which I have initialized by dereferencing the pointer passed from the gameobject. But this won't work while updating the values.

1

There are 1 best solutions below

2
Alex On

The simplest solution is using std::shared_ptr<T> instead of raw pointer.

class Collider {
public:
  Collider(std::shared_ptr<Transform> _transform):transform(_transform){
  }
private:
  std::shared_ptr<Transform> transform;
};

class GameObject {
public:
   GameObject(std::shared_ptr<Transform> transform) : collider(transform) {
   }
private:
   std::shared_ptr<Transform> transform;
   Collider collider;
};

In this case Collider and GameObject will share the ownership over Transform instance and a default generated copy/move constructor/assignment will will give you necessary functionality.

On the other hand if you want not to share ownership, you can put Transform instance into Collider and make it accessible to GameObject with getter function.

Everything depends on the design (it's pretty hard to me understand it from small part of code).