Re: virtual function in inherited class not getting called
On 10 Apr, 10:34, alasham.s...@gmail.com wrote:
On Apr 10, 11:22 am, Angus <anguscom...@gmail.com> wrote:
I have a base class CEventSelect a bit like this:
class CEventSelect
{
virtual void OnConnected();
}
and a network interface class a bit like this:
class networkinterface : public CEventSelect
{
virtual void OnConnected();
}
The base CEventSelect class calls it's OnConnected() function when a
client receives notification from the network that it is connected.
But I wanted my networkinterface::OnConnected() method to be called?
But it wasn't. I understand polymorphic functions and I think I
understand why it is not working the way I wanted. Because
CEventSelect calls its own OnConnected() method does mean that the
inheriting OnConnected() will be called. But this is the behaviour I
want.
The actual connection is notified by the base class - but I want my
interface class to someone get notified of the connection.
How can I get the networkinterface class to be notified about the
connection?
Polymorphic function dispatch mechanism requires the use of pointers
or references. The following should work.
Regards.
#include<iostream>
class CEventSelect
{
public:
virtual void OnConnected() { std::cout <<
"CEventSelect::OnConnected()\n"; }
};
class networkinterface : public CEventSelect
{
public:
virtual void OnConnected() { std::cout <<
"networkinterface::OnConnected()\n"; }
};
int main()
{
CEventSelect* p = new networkinterface();
p->OnConnected();
delete p;
std::cin.get();
}- Hide quoted text -
- Show quoted text -- Hide quoted text -
- Show quoted text -
You misunderstand my question. I am not calling OnConnected from
networkinterface. OnConnected() is called from an event inside
CEventSelect. That is my problem. But I want the networkinterface
class to be notified of the OnConnected 'event' happening.
So my notification event is happening in my base class. Of course the
base class knows nothing of networkinterface - hence OnConnected() in
networkinterface is not called.
Maybe virtual functions are not the right answer here. Maybe I need
to notify some other way?