Search code examples
c++constructorstatic-variables

How does reassigning static variables work?


Since the lifetime of a static variable is that of the program what exactly happens when you try to reassign it?

Some how in the program below, the test.loc ends up becoming 6 before getting destroyed eventhough the constructor is the only thing that can change that value. It is the original object itself so how does one of it's member variables change?

#include <iostream>

class Test
{
public:
   int loc = 0;

   Test()
   {
      std::cout << "Constructed!" << loc << "\n";
   }

   Test(int j)
   {
      loc = j;
      std::cout << "Constructed!" << loc << "\n";
   }

   ~Test()
   {
      std::cout << "Destroyed!" << loc << "\n";
   }
};

static Test test;


int main()
{
   // Write C++ code here

   test = Test(6);


   return 0;
}

Output:

Constructed!0
Constructed!6
Destroyed!6 // this is the locally constructed variable
Destroyed!6 // This is the static variable getting destroyed

Solution

  • Your program does not define an assignment operator (operator=), so the compiler creates one for you. That assignment operator will copy the value of loc from the source instance of Test and will change the value of loc in the destination instance.

    If you add the following to your Test class, you'll see what is happening:

    Test &operator=(const Test &src) {
        std::cout << "Assigned!" << loc << "<-" << src.loc << "\n";
        // this is what the default assigment operator does:
        loc = src.loc
    }