I am attempting to automate the testing of Employee class (see code below).
Each iteration of the loop is a new test case.
Each iteration of the loop instantiates and destroys employee objects to insure that each test case starts in an initial state.
The following code runs, but the static manager persists across test cases.
Is there a way to instantiate and destroy static manager object in the loop?
I need to insure that manager object starts in initial state for each test case.
#include <iostream>
class Manager
{
private:
int j;
public:
void print() { std::cout << " " << j++; }
};
class Employee
{
private:
static Manager& refManager; //declare class static variable in class
public:
void fn() { refManager.print(); }
};
Manager manager;
Manager& Employee::refManager = manager; //initialize static variable outside of class
int main()
{
for (int i=0; i<2; i++) //test loop, one testcase per iteration
{
Employee e1; //Employee objects being tested
Employee e2;
//expected output
e1.fn(); // 0
e2.fn(); // 1
/*Employee destructor is automatically called
because its scope of existence has finished */
}
}
Add method to Manager which will reset internal state.
Another way is to manually destroy object (by calling a destructor) and recreate it (by using placement new)
I am surprised that works, but it does.
It's as if line 29 (below) is copy by value.
But the syntax on line 17 says copy by reference.
What is happening?
I get the feeling that there is some fundamental C++ rule needed to make sense of the above two examples.
The only difference is that 'manager' is global scope while 'manager1' is local scope.
This is copy by reference (line 28 posted 9:56pm): Employee::refManager = manager; //manager is global
Is this copy by value? (line 29 posted 8:42pm): Employee::refManager = manager1;//manager1 is instantiated locally
The syntax is the same. What C++ rule causes manager1 to copy by value?
Manager manager;
Manager& Employee::refManager = manager;
//This makes Employee::refManager an alias for manager
//When you are changing refManager, you are actually changing manager
//You can substitute Employee::refManager with manager
//and (assumung both are visible) it will behave the same
So Employee::refManager = manager; can be rewritten as manager = manager; Do you see the problem now?