Attempting to post an easier to read/debug example of a question I posted earlier. The A-object in main.cpp, which is passed by reference into a B-object seems to end up being a copy of the original A-object; that is to say operations performed on the A-object within the B-object do not affect the instance of the A-object created in the main.cpp. Given the print commands in the main.cpp, it prints the following: 17, 17, 42, 17; when I would expect the program to print 17, 17, 42, 42.
[main.cpp]
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
A a = A();
B b = B();
a.setNumber(17);
b.setA(a);
cout << a.getNumber() << endl; //prints 17
cout << b.getNum() << endl; //prints 17
b.changeNumber(42);
cout << b.getNum() << endl; //prints 42
cout << a.getNumber(); //prints 17
}
[A.cpp]
void A::setNumber(int num)
{
number = num;
}
int A::getNumber()
{
return number;
}
[B.cpp]
void B::setA(A &aObj)
{
a = aObj;
}
void B::changeNumber(int num)
{
a.setNumber(num);
}
int B::getNum() {
return a.getNumber();
}
[[Fields]]
[A.h] int number;
[B.h] A a;
Thank you for reading!