0

Possible Duplicate:
What does it mean to have an undefined reference to a static member?

I have a static class as follows:

.h file

class c1 {
    public:
    static int disconnect();
    private:
    static bool isConnected;
    };

.cpp file

#include c1.h

int c1::disconnect()
{
    c1::isConnected = false;
    return 0;
}

However when I compile, there is an error

undefined reference to `c1::m_isConnected'

Please help!

Community
  • 1
  • 1
user623879
  • 4,066
  • 9
  • 38
  • 53

3 Answers3

2

You have to provide an actual object instance for the static class members. Add the following to your .cpp file:

 bool c1::isConnected;

To initialize it to a specific value, add an initializer:

 bool c1::isConnected = false;

(By the way, classes in C++ cannot be static. Classes are just types. Only class members can be static.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Isn't the "m_" caused by name mangling? –  Sep 11 '11 at 22:10
  • sweet thx...im coming form C#/C so yeah.. – user623879 Sep 11 '11 at 22:13
  • Not sure about C#, but Java has static classes... in C++, any class that's defined inside another class is called a "nested class". But there's no analogue of a "static (nesterd) class" in C++, i.e. a class that only static member functions can use -- the concept doesn't make sense in C++, where classes are just types. – Kerrek SB Sep 11 '11 at 22:15
1

isConnected is a (non-static) member variable and you can't use it without an instance that it's a part of. While static variables exist independently of any object, non-static member variables only exist as part of an instance of that class.

You need to either make isConnected static or accept an instance of c1 on which to set isConnected to false. You probably want the former.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
0

What you have in header file is declaration. However, you also need a definition of the variable. The correct code will look like this:

class c1 {
public:
    static int disconnect();
private:
    static bool isConnected;
};

bool c1::isConnected = false;

int c1::disconnect()
{
    isConnected = false;
    return 0;
}
  • It's important to get the separation of header file and source file right, though, otherwise you might end up with multiple definitions. – Kerrek SB Sep 11 '11 at 22:13