Referencing object from another class doesn't updates the object values

Viewed 27

I am trying to reference a class object from another class. So I have this: In A.h

#ifndef AAA
#define AAA


#include "B.h"
#include "C.h"
class A
{
public:
    B Bobject1 = B();
    C Cobject = C();
    void foo1();
};

extern A Aobject;
#endif // AAA

In A.cpp

#include "A.h"
A Aobject;

In B.h

#ifndef BBB
#define BBB

#include <iostream>
using namespace std;
class B
{
public:
    B(){}
    int val;
    void foo2(int num)
    {
        val = num;
        cout<<val<<endl<<endl;
    }
};
#endif // BBB

And here is the real stuff. In C.h

#include <iostream>
#include "B.h"
using namespace std;

class C
{
 public:
     B &pBobject;
     C():pBobject(*new B)
     {

     }
     void foo3(void)
     {
          pBobject.val = 12;
          cout<<pBobject.val<<endl;
     }
};

Finally, my main function looks something like this:

#include "A.h"

int main()
{
    Aobject.Bobject1.foo2(6);
    cout<<"Before  " << Aobject.Bobject1.val<<endl;    // this prints 6
    Aobject.Cobject.foo3();                            // I internally assign 12 to B class variable
    cout<<"After  " << Aobject.Bobject1.val<<endl;     // It still holds 6.
    return 0;
}

In debug session, I can see the reference variable holds 12 after this line

Aobject.Cobject.foo3()

However, that doesn't update the B class object to which it is referencing. That clearly means it is using a different address space than the Class B object created inside Class A.

What I am doing wrong here? Thanks in advance.

0 Answers
Related