Is there a way to force Class to reinitialize?

I am testing a class in a loop, where each iteration of the loop will start a new test case.
Each iteration of the loop needs to start with the class in it's initial state.

The code below instantiates and destroys the 'a' object in the loop.
This insures that the object's non-static variables are in initial state.
But the static variable values persist.
Is there a way to force the class or it's static variables to reinitialize?
Changing the classes being tested is not an option.

Thank you.

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

class ClassA
{
	private:
		static int val;		// static class value persists independent of object
	public:
		void testCase() { val++; }
		void print() { std::cout << "val=" << val << std::endl; }
};
int ClassA::val=0;

int main()
{
	for (int i=0; i<3; i++)
	{
		ClassA a;		//instantiate 'a' object locally
		a.print();		//print initial state
		a.testCase();
		a.print();		//not initial state
	}
}

out put:
val=0
val=1
val=1
val=2
val=2
val=3
Last edited on
You seem to have some misconception about static class variables.
1
2
3
4
5
6
7
class ClassA {
    static int val;
public:
    static void reset() {
        ClassA::val = 0;
    }
};


http://coliru.stacked-crooked.com/a/603aa5584b13b815
as Smac89 showed, there is way of doing that by using static function, but class function is an option as well.

Thank you Smac89. That worked.
Topic archived. No new replies allowed.