What is the output of the following code snippet?

class test {
public:
static int n;
test () { n++; };
~test () { n--; };
};

int test::n=0;
int main () {
test a;
test b[5];
test * c = new test;
cout << a.n << endl;
delete c;
cout << test::n << endl;
return 0;
}

Options
- 7 6
- 6 7
- 5 6
- 6 5


CORRECT ANSWER : 7 6

Discussion Board
Appreciate

Thank you Maxime.. for explaining that question in a good and effective way


Tushar 09-24-2017 05:05 AM

C++ Static key word

Class with static member variable will not created whenever a new object is created for the same class. All objects of the class "test" will access same static member variable. i.e. static int n. And also static variable are declared and defined only once during the program execution, hence values for static int n value increases

sangaraj 09-5-2017 01:47 PM

explaination

n is a static variable

int test::n=0; // initialized has default

the default constructer of class TEST increase n++

So


test a; // n now = 1 because the constructer increased it
test b[5]; // n now = 6 because the array initialized it by default 5 times ( 5 time n++ )
test * c = new test; // n now 7 because a new test is created and the constructer does n++
cout << a.n << endl; print 7
delete c; // destructer does n-- so it remove 1
cout << test::n << endl; // print 6


So the answer is 7 6

Maxime 10-16-2015 11:18 PM

c++

Please give explanation of above question . I did not get it how it comes

vinayak 09-21-2015 08:52 AM

problem

plz give explanation of this question

priya 09-13-2015 09:02 AM

Write your comments


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement