views:

3606

answers:

4

Very simply put:

I have a class that consists mostly out of static public members, so I can group similar functions together that still have to be called from other classes/functions.

Anyway, I have defined two static unsigned chars in my class' public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.


class test {

    public:

     static unsigned char X;
     static unsigned char Y;

     ...

     test();
};

test::test() {
    X = 1;
    Y = 2;
}

I'm new to C++ so go easy on me. Why can't I do this?

+8  A: 

You forgot to add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

Colin Jensen
+4  A: 

Static data members declarations in the class declaration are not definition of them. To define them you should do this in the CPP file to avoid duplicated symbols.

The only data you can declare and define is integral static constants. (Values of enums can be used as constant values as well)

You might to rewrite you code as:

class test {
public:
  const static unsigned char X = 1;
  const static unsigned char Y = 2;
  ...
  test();
};

test::test() {
}

If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:

.H :

class test {
public:

  static unsigned char X;
  static unsigned char Y;

  ...

  test();
};

.CPP :

unsigned char test::X = 1;
unsigned char test::Y = 2;

test::test()
{
  // constructor is empty.
  // We don't initialize static data member here, 
  // because static data initialization will happen on every constructor call.
}
sergdev
A: 

Refer to http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.11 You may want to read up on the rest of FAQ.

Vinay Y S
+1  A: 

Since you say you are a noob, I'll just add to the other answers that a class of "mostly public static members" is a red flag for 'maybe you should rethink your design'. Of course there are cases where this is necessary - but not many. Usually it means your design lacks encapsulation, cohesion etc. Without more details on what you are doing it is hard to be more specific.

Steve Fallows