This is a condensed version of a problem I came across today, can
anyone explain what is going on?
If the code below is run nothing will be output (in the original
problem it was causing exeptions).
if all the virtual destructors are commented out it outputs 'e'
or if
"class InterfaceImpl : public Base, public Interface"
is changed to
"class InterfaceImpl : public Interface, public Base"
it also outputs 'e'
in the default case (ie that below) *p refers to a "Base" then
p->recvSignal() causes the problem. Why is it not referring to an
"Interface". And to me more strangely why does it then refer to an
"Interface" if the virtual destructors are removed?
Thanks in advance for any responses - it will probably be monday before
I get to look at them.
Also at the moment the problem has been worked around simply by
altering the order of the inherited classes as noted above. Is this
safe?
#include <iostream>
using namespace std;
class Interface
{
public:
virtual void recvSignal(char ch) = 0;
virtual ~Interface(){};
};
class Controller
{
public:
void doit()
{
p->recvSignal('e');
};
void addDevice(void* ptr)
{
p = (Interface*)ptr;
};
virtual ~Controller(){};
private:
Interface* p;
};
class Base
{
public:
void nv(){};
virtual ~Base(){};
};
class InterfaceImpl : public Base, public Interface
{
public:
void recvSignal(char ch)
{
cout<<ch<<endl;
};
virtual ~InterfaceImpl(){};
};
class Controlled : public InterfaceImpl
{
public:
void nvgb(){};
virtual ~Controlled(){};
};
int main()
{
Controller ctrl;
Controlled device;
ctrl.addDevice(&device);
ctrl.doit();
return 0;
}