Problems using MidiKeyboardComponent (resolved!)

I'm seeing a problem using MidiKeyboardComponent. I've copied code out of the demo and ended up with this MainContentComponent:

The header MainContentComponent.h

class MainContentComponent   : public Component
{
public:
    //==============================================================================
    MainContentComponent();
    ~MainContentComponent();
    void paint (Graphics&) override;
    void resized() override;
private:
    MidiKeyboardComponent keyboard;
    MidiKeyboardState state;
    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainContentComponent)
};

The source: MainContentComponent.cpp

MainContentComponent::MainContentComponent() 
    : keyboard(state, MidiKeyboardComponent::horizontalKeyboard)
{
    addAndMakeVisible(keyboard);
    setSize (800, 600);
}

MainContentComponent::~MainContentComponent()
{
}

void MainContentComponent::paint (Graphics& g)
{
    g.fillAll (Colour (0xffeeddff));
}

void MainContentComponent::resized()
{
    keyboard.setBounds(0, getHeight() - 64, getWidth(), 64);
}

The problem is when I run I get the following:


First-chance exception at 0x00594270 in SynthesizerSample.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD.
Unhandled exception at 0x00594270 in SynthesizerSample.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD.

>    SynthesizerSample.exe!juce::Array<juce::MidiKeyboardStateListener *,juce::DummyCriticalSection,0>::contains(juce::MidiKeyboardStateListener * elementToLookFor) Line 374    C++

     SynthesizerSample.exe!juce::Array<juce::MidiKeyboardStateListener *,juce::DummyCriticalSection,0>::addIfNotAlreadyThere(juce::MidiKeyboardStateListener * newElement) Line 533    C++
     SynthesizerSample.exe!juce::MidiKeyboardState::addListener(juce::MidiKeyboardStateListener * listener) Line 177    C++
     SynthesizerSample.exe!juce::MidiKeyboardComponent::MidiKeyboardComponent(juce::MidiKeyboardState & s, juce::MidiKeyboardComponent::Orientation o) Line 100    C++

I just realised what the actual problem is - the order of the declarations. I had:

MidiKeyboardComponent keyboard;
MidiKeyboardState state;

When I switched the order:

MidiKeyboardState state;
MidiKeyboardComponent keyboard; 

The problem goes away! I'm guessing state is being used before it's constructor has executed, hence the 0xCDCDCDCD.

THX A LOTTTTT!!!
As a green hand, i’ve been confused by the trouble for an entire morning…