How to handle static variable in class?

I want to test the behavior how constructors, assignment operators and destructors get invoked. I tried to use a static variable inside a class, but i get this linker error:
undefined reference to `Foo::ctr'

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>

using namespace std;

struct Foo
{
    static int ctr;
    
    int m_objNr;
    
    Foo()
    { 
        m_objNr = ++ctr;
        cout << "Object "<< m_objNr
             << ": I'm the default constructor.\n";
    }
    Foo( Foo& other)
    {
         m_objNr = ++ctr;
         cout << "Object "<< m_objNr
              << ": I'm the copy constructor.\n";
    }
    Foo operator= ( Foo& other)
    { 
        cout << "Object " << m_objNr
             << ": I'm the assignment operator.\n";
        return other;
    }
    ~Foo()
    {
         cout << "Object " << m_objNr
              << ": I'm the destructor.\n";
    }
};

int main()
{
    Foo::ctr = 0;
    Foo foo;
    std::cout << "--------\n";
    Foo bar = foo;
    std::cout << "--------\n";
    foo = bar;
    std::cout << "--------\n";
}
You need to create the int object known as Foo::ctr somewhere.
How do you mean this? I thought that I have created Foo::ctr at line 38. Please could you fix my code such that it compiles and links.
Just put this between struct Foo and main:

 
int Foo::ctr = 42;  // initialize it here too (or don't and it will automatically initialize to zero) 

Also, operator= should return *this (not other). And other should be const:

1
2
3
4
    Foo operator= (const Foo& other) {
        cout << "Object " << m_objNr << ": assignment operator.\n";
        return *this;
    }

Last edited on
Topic archived. No new replies allowed.