0

How do we store a pointer that was passed by reference to get modified in C++?

class A {
private:
   reference_to_a_pointer_; ???
   bool useSpecialAPI_;

public:
   void useSpecialAPI(mytype_t *&recvd_data);
   void init();
};

void A::useSpecialAPI(mytype_t *&recvd_data)
{
   useSpecialAPI_ = true;
   reference_to_a_pointer_ = recvd_data; ???
}

void A::init()
{
   if (useSpecialAPI_) {
      // specialAPI() returns a "void*"
      reference_to_a_pointer_ = (mytype_t *)specialAPI();
   }
}   

In main(), I'm doing,

int main ()
{
   mytype_t *recvd_data = NULL;

   A a;
   a.useSpecialAPI(recvd_data);
   a.init();

   if (recvd_data) {
      parseData(recvd_data);
   }
   
   return 0;
}

I'm passing recvd_data pointer by reference, for it to get populated in init() function later. I would need to store it in the class member variable. How can I store it and assign it a value later? I would like to avoid modifying or overloading the prototype of init().

void
  • 338
  • 5
  • 19
  • 1
    You cannot rebind a reference. What you do in `useSpecialAPI` is incorrect. Either use a double pointer or do it in `A`'s constructor. – Nelfeal Oct 04 '22 at 12:04
  • References can be initialized only ***once*** within constructor initializer lists. – πάντα ῥεῖ Oct 04 '22 at 12:04
  • 6
    I know you think `init` is special, but only because you named it `init`. You can actually call that function as many times as you'd like. In so doing, you would be "reassigning" a reference, which is impossible by design in C++. If your method is really _initialization_ then you should assign the reference once in the _constructor_ for `A`. Perhaps have a look at [this question](https://stackoverflow.com/questions/7713266/how-can-i-change-the-variable-to-which-a-c-reference-refers) which is not only informative but also suggests using `std::reference_wrapper`. – Wyck Oct 04 '22 at 12:07

0 Answers0