-4
#include<iostream>
using namespace std;
class abc
{
    static int x;
    public:
        abc()
        {
            x++;
        }
    static int getx()
    {
        return x;

    }
};
int abc::x=0;
int main()
{
    cout<<abc::getx()<<" ";
    abc t[10];
    cout<<abc::getx();

}

While going through the mcqs of Techgig event in india i had problem on the following code. Help me understand the following code. what does the line abc t[10] means?

Blaze
  • 16,736
  • 2
  • 25
  • 44
Aditya Roy
  • 13
  • 2

1 Answers1

3

what does the line abc t[10] means?

It means that you get 10 abc on the stack and that you will refer to them by t. Just like int t[10] gets you 10 int, except instead of int, it's abc.

But you probably wondered what this example is supposed to demonstrate with it. We have a static variable in class abc, so this one exists only once, no matter how many abc are made:

static int x;

It is set to 0 here:

int abc::x=0;

At the start of the program we confirm that it indeed is 0:

cout<<abc::getx()<<" ";

This should print 0, because it's calling a static getter that returns that x value:

static int getx()
{
    return x;
}

Now, what's happening here?

abc t[10];

Here, 10 abc are made. Actually, in reality not much might be made here because abc doesn't have any non-static fields. But nevertheless, the constructor is called every time:

abc()
{
    x++;
}

Remember, 10 abc are made, so this is called 10 times. Thus, x is increased by 1 ten times, and since it was 0, it should now be 10. We confirm this assumption with the following print:

cout<<abc::getx();
Blaze
  • 16,736
  • 2
  • 25
  • 44