Home > OS >  Using a pointer to an object as a member of another object
Using a pointer to an object as a member of another object

Time:01-20

For certain reasons, I want to have multiple instances of class A all have access to a single instance of class B. B has public member functions that allow objects of A to get data from B, but not to change it. I'm trying to do this by declaring an object of B in my main function, then passing it to the constructor when I declare objects of type A.

void main () {
  B obj_b;
  A A1(obj_b);
  A A2(obj_b);
  A A3(obj_b);  

  cout << A1.getfoo() << endl;
  cout << A2.getfoo() << endl;
  count << A3.getfoo() << endl;
}

class B{
  private:
    int foo = 9;
  public:
    int getfoo(){return foo;}
};

class A {
  private:
    B *bptr;

  public:
    A(B b){ this->bptr = &b; }
    int getfoo(){ return bptr->getfoo(); }
};

This compiles and runs, but I get very weird results. The return values from getfoo are sometimes correct sometimes incorrect. Am I handling the pointers incorrectly? Is there a better way to do this?

CodePudding user response:

In the A constructor, the argument b is a local variable, its life-time ends when the constructor function ends. You can't save a pointer to it, that pointer will become invalid immediately.

Either use smart pointers, or use a reference and constructor initializer lists:

class A
{
public:
    // Pass by reference
    A(B& b)
        : b{ b }  // Initialize the member variable b with the argument b
    {
        // Empty body
    }

private:
    B& b;  // Reference to a B object
};
  • Related