user3129763
user3129763

Reputation: 25

How to access private static class member inherited from a template class?

I'm trying to access static variable inherited from the EventListener template, but it looks like the derived KeyboardListener class is not a friend of EventDispatcher. What am I doing wrong?

template <class T>
class EventListener
{
public:
    friend class EventDispatcher;
private:
    static int variable;
};

template <class T> int EventListener<T>::variable;

class KeyboardListener : EventListener<KeyboardListener> {};

class EventDispatcher {
    public:
        static void foo() {
            // this works
            std::cout << &EventListener<KeyboardListener>::variable << std::endl;
            // fails to compile with: 
            // 'int EventListener<KeyboardListener>::variable' is private
            std::cout << &KeyboardListener::variable << std::endl; 
        }
};

Upvotes: 2

Views: 97

Answers (3)

NathanOliver
NathanOliver

Reputation: 181068

The default inheritance of classes is private. When you have

class KeyboardListener : EventListener<KeyboardListener> {};

You are inheriting privately from EventListener all the EventListener members are private. I think you ment to inherit publicly like

class KeyboardListener : public EventListener<KeyboardListener> {};

Live Example

Upvotes: 1

Your problem is that EventListener<KeyboardListener> is a private base class of KeyboardListener (KeyboardListener is decalred using class, and you didn't specify the public keyword when deriving from the base class). So the conversion from KeyboardListener to EventListener<KeyboardListener> can only be done by someone who can access the private members of KeyboardListener, which EventDispatcher can not.

I'd hazard a guess the private inheritance is accidental and not what you wanted. But if it is actually desired, you will have to declare EventDispatcher as a friend in KeyboardListener as well.

Upvotes: 3

GreatAndPowerfulOz
GreatAndPowerfulOz

Reputation: 1775

Try this:

class KeyboardListener : EventListener<KeyboardListener> {
    friend class EventDispatcher;
};

Upvotes: 0

Related Questions