Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a static class data member declared as:

static const float MINIMUM_ZOOM_FACTOR = 4.0;

I'm using this constant in a class member function like this:

zoomFactor_ = max(zoomFactor_, MINIMUM_ZOOM_FACTOR);

At this point, the compiler complains that MINIMUM_ZOOM_FACTOR is an undefined reference. However if I use it directly like this:

if(fabs(zoomFactor_ - MINIMUM_ZOOM_FACTOR) < EPSILON) ...

it works a-ok. What am I doing wrong?

share|improve this question
    
Post some compilable code that illustrates exactly what you are doing. – anon Jul 8 '10 at 9:24
    
My guess is that you second example is in the same file as the declaration of MAXIMUM_ZOOM_FACTOR and your first isn't. The static prevents it from being used outside its source file. – Job Jul 8 '10 at 9:27
    
@Job No because it's a static class member, and therefore the meaning of static is not the same... – Joan Rieu Jul 8 '10 at 9:41
    
Is it compiler or linker error? I guess max is a template with parameters passed by const reference. This may trigger a compiler to think that you must allocate storage for MAXIMUM_ZOOM_FACTOR and you probably did not. Put MAXIMUM_ZOOM_FACTOR definition in .cpp file and see if that fixes it (do not include = 4.0 thou). – Tomek Jul 8 '10 at 10:33
up vote 4 down vote accepted

Only integer constants can be defined inside the class like that. Floating point (or class type) constants must be declared in the class, and then defined and initialised once outside. In practice, that means you must define it in a source file.

// header file
class thingy
{
    static const float MAXIMUM_ZOOM_FACTOR;
};

// source file
const float thingy::MAXIMUM_ZOOM_FACTOR = 4.0f;

As to why direct use works but max doesn't: max takes its arguments by reference, so it may require the address of the constant object. If you haven't defined the object then that won't work. Direct use might substitute it for a compile-time constant, which doesn't require an address.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.