practice test ans 7,6

Feb 13, 2013 at 1:46pm
I was working a practice test. Snippet of code gives answer of 7,6. Can't see it, i get 1,0

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;
}
Feb 13, 2013 at 1:52pm
7 and 6 looks right by my count.

What aren't you getting?
Feb 13, 2013 at 2:06pm
for cout << a.n << endl i am getting a 1. For object a of class test type, test::n=0, so calling a.n, n++ increments n=0 by 1 for the first answer by my analysis
Feb 13, 2013 at 2:13pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class test{
public:
   static int n;
   test() {n++;};
   ~test(){n--;};
};

int test::n=0;

int main(){
   test a;   // Object created on stack, n++
   test b[5]; // 5 stack objects created, n+=5
   test *c = new test; // Heap object created, n++
   cout << a.n << endl; // Print n (7)
   delete c; // Heap object deleted, n--
   cout << test::n << endl; // Print n(6)
   return 0;
}
Feb 13, 2013 at 2:30pm
ok, i think i get it. So each time of type class object created on stack, constructor increments due to static int n;

thx iHutch105!!
Feb 13, 2013 at 2:33pm
Exactly. Because n is static, there is only one instance of it shared between each instance of the class.

Every time an object is created (stack or heap) the constructor runs and n is incremented. When the object is destroyed, as it is in the delete line, the destructor runs and n is decremented.
Feb 13, 2013 at 2:39pm
i get it. i missed the static int n of the class. I also missed the significance of constructor relative to the 3 objects. Didn't realize the commonality of the contructor incrementing class var n, regardless of object. thx again!!
Feb 13, 2013 at 2:42pm
More precisely it would be said that whenever the default constructor is called the static data member is increased. Take into account that you did not define explicitly a copy constructor. So whenever an object is created due to a copy constructor the static member will not be increased. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

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

int test::n;

int main()
{
   {
      test a1;

      std::cout << test::n << std::endl; // n == 1

      test a2( a1 );

      std::cout << test::n << std::endl; // n == 1
   }

   std::cout << test::n << std::endl; // n == -1

   return 0;
}


The last value of test::n will be equal to -1
Last edited on Feb 13, 2013 at 2:43pm
Topic archived. No new replies allowed.