0
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:

  1. is applying B b2(b1) is the same as B b2 = b1 always ? or some cases this wont work ?
  2. *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 :)

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    The pointer to x points to the same location because of the violation of the rule of 3 / 5 /0. Related: [https://en.cppreference.com/w/cpp/language/rule_of_three](https://en.cppreference.com/w/cpp/language/rule_of_three) – drescherjm Apr 30 '21 at 18:08
  • 2
    `B b2(b1)` is instantiating `b2` using the copy constructor, which is nearly similar to the assignment operator, and it's equivalent in this case. When not explicitly defined by the class, the default copy constructor for a class is to initialize the class doing a member by member - invoking the copy constructor on each from the other instance. – selbie Apr 30 '21 at 18:12
  • `*` returns a reference by default. – bipll Apr 30 '21 at 18:24

0 Answers0