What will be displayed as a result of the program execution?
#include <iostream>

class A {
   int count;

public:
   A() : count(0) { }
   A(A & a) : count(a.count+1) {}

   A & operator = (A & a) {
      return count *= 10, *this;
   }

   void print() {
      std::cout << count;
   }
};

int main(int argc, char * argv[]) {
   A a, b = a, c = b = b, d = c = c = c;
   c.print();
}
Explanation
Creating a, default constructor, a.count = 0
Creating b, copy constructor, b.count = a.count + 1 = 1
The creation of c should be considered as c = (b = b), i.e. before initializing c, the expression on the right side of the = operator needs to be calculated, i.e. first, the assignment operator b + b is triggered, followed by b.count = 10. And then the copy constructor for c = b (with the new count), i.e. c.count = b.count + 1 = 10 + 1 = 11.
Creating d. By analogy, c = c = c is computed first, i.e. two assignment operators, where we get c.count = c.count * 10 * 10 = 11 * 10 * 10 = 1100. The d may be not calculated further.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты