class A {
public:
int* x;
};
class B {
public:
A _a;
};
int main()
{
B b1;
b1._a.x = new int(1);
B b2(b1);
*b2._a.x = 2;
std::cout << *(b1._a.x) << std::endl;
}
hi i, have this block of code, which i need to understand. i know that at the end the answer in 2. what i assumed that happened is we created 2 objects of type B , b1 and b2.
b1._a.x = new int(1); // this line sets the field x of object _a of b1 to point to a block of memory of 1 int.
B b2(b1); // here we assigned b2=b1 now b1 and b2 have the same fields which means their field _a is the same object , which means that the field x of _a in both objects is the same so they point to the same place in memory. so when we set the x field of _a of b2 , it automatically set the x field of _a of b1 to the same value which is 2.
did i explain this right ? have i missed anything ? i have 2 questions about the code in general:
- is applying B b2(b1) is the same as B b2 = b1 always ? or some cases this wont work ?
- *b2._a.x = 2; i know that the use of * before a pointer is for derefrencing the pointer , (to get a value from some pointer). so why are we allowed to assign values into it (is it considered a refrence)?
Thanks :)