The output of this piece of code is
21
I am unable to explain it to myself. My thinking (what I learned) is that an implicit copy constructor is called (triggered by the assignment) and all elements are copied bit by bit. However this does not apply to external elements, like the private variable val
, which is a pointer. So b
has a different pointer, but it is pointing to the same element.
So I expected the result to be
22
That is .get()
is called twice by a
and b
and thus the dereferenced pointer value should be 1
(after the first get()
) and then 2
(after the second get()
). Finally the values are written to the console output.
C++ code:
#include <iostream>
using namespace std;
class A {
int *val;
public:
A() {
val = new int;
*val = 0;
}
int get() {
return ++(*val);
}
};
int main() {
A a, b = a;
cout << a.get() << b.get();
return 0;
}