+ 1
What will be printed after the code run?
8 Answers
+ 1
that's ok, thanks
0
answer without run;)
0
Is this a challenge or do you need help?
0
sorry, i don't know how do the challenge...
- 1
? Just click the run button.
- 1
It's 12 ({1,2}) because a is static. This means, it's a global variable which can only be accessed within the function. I believe it's constructed with the first call.
- 1
Did you understand the code with my explanation?
- 1
Anyways, here is a detailed explanation (already did the work):
#include <iostream>
using namespace std;
class A
{
public:
void test()
{
static int a = 0; // static: not object dependent, stays forever.
cout << ++a; // equivalent to: a = a + 1; cout << a;
}
};
int main() {
A a;
A b;
a.test(); // Output: 1 (0 + 1)
b.test(); // Output: 12 (1 and 1 + 1)
}