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?
 
    