Reputation: 25
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
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> {};
Upvotes: 1
Reputation: 171197
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
Reputation: 1775
Try this:
class KeyboardListener : EventListener<KeyboardListener> {
friend class EventDispatcher;
};
Upvotes: 0