Can't define Colour as static const member variable

This looks like it should be basic, but I’m having trouble defining a Colour as a static const member variable. I’m setting it in global scope, as is the way with static const member variables, but it doesn’t seem to work with Colour.

class ExampleComponent : public Component
{
    static const Colour exampleColour;

    void resized() override
    {
        DBG(exampleColour.toString());
    }
};

const Colour ExampleComponent::exampleColour = Colours::aliceblue;

This always prints 0 for me. Can anyone explain why?

This is due to the indeterminate order of static initialisation. Static data in different TUs may be initialised in any order, and in this case, your Colour is being initialised before the juce Colours have been set up. If you use Colour’s hex/RGB constructor instead of the copy constructor, this should work.

3 Likes

I’ve ran into the static initialization order fiasco before, but hadn’t considered that it would also affect things in the JUCE headers. Seems so obvious now. Thanks for the advice.

There’s a change on develop now that should avoid this initialisation-order issue with juce::Colours. Now you can initialise your own const Colour from one of the juce::Colours without worrying about initialisation order.

3 Likes