tags:

views:

106

answers:

1

Hi guys, what's wrong with the following code:

class A
{
public:
 static A* p;

 A()
 {
  p = this;
 }
};

I got this link error:

error LNK2001: unresolved external symbol "public: static class A * A::p" (?p@A@@2PAV1@A)

I cannot figure out the point of this problem, please help..

+12  A: 

You need storage for that pointer. You declared, but did not define it. In the implementation (.cpp) file do:

A* A::p;

Edit 0:

By the way, do you really want to override that pointer every time a new instance of your class in created? Seems to me you are looking for the Singleton pattern.

Edit 1:

You can initialize static variables (and not unlike in Java, come to think of it, though the syntax is different). Say you have a static string member foo of a class X, then your implementation file might contain the following:

std::string X::foo = "Happy Leif Erikson Day!";

But be careful - constructors for static objects run before main() is entered and their order between translation units is undefined, which often leads to "static initialization order fiasco".

Nikolai N Fetissov
+1. I would reccomend adding = NULL though
Akusete
It's static, it's zero by definition.
Nikolai N Fetissov
It works!! Is it because when I create an object, the static variable is not allocated? So I have to write codes to instantiate the static variable? Can I write a static field like in Java to initialize the static variables?
Alan
+1 for your intuition on Singleton
Chubsdad
for sure he wants the singleton
fabrizioM