using namespace std;
class Layer
{
protected:
Layer *lower;
Layer *upper;
public:
Layer(Layer *lo,Layer *up):lower(lo),upper(up)
{}
virtual void send()=0;
virtual void receive()=0;
};
class Physical_Layer:public Layer
{
public:
Physical_Layer(Layer *p):Layer(NULL,p)
{
cout<<"Physical_Layer constructed"<<endl;
}
virtual void send()
{
cout<<"Data send from Physical_Layer"<<endl;
receive();
}
virtual void receive()
{
cout<<"Physical_Layer calling receive of DataLink_Layer"<<endl;
upper->receive();
}
};
class DataLink_Layer:public Layer
{
public:
DataLink_Layer(Layer *p):Layer(new Physical_Layer(this),p)
{
cout<<"DataLink_Layer Constructed"<<endl;
lower->send();
}
virtual void send()
{
cout<<"Data send from DataLink_Layer"<<endl;
lower->send();
}
virtual void receive()
{
cout<<"DataLink_Layer calling receive of Application_Layer"<<endl;
cout<<typeid(upper).name()<<endl;
upper->receive();
}
};
class Application_Layer:public Layer
{
public:
Application_Layer():Layer(new DataLink_Layer(this),NULL)
{
cout<<"Application_Layer Constructed"<<endl;
send();
}
virtual void send()
{
cout<<"Sending data from Application_Layer"<<endl;
lower->send();
}
virtual void receive()
{
cout<<"Receiving data at Application_Layer"<<endl;
}
};
int main()
{
Layer *l=new Application_Layer();
}
I was trying to simulate a three layer protocol stack using the Protocol Design Pattern. But while dereferencing the upper->receive in DataLink_Layer’s receive i am getting a run time exception: System.AccessViolationException. Why am i getting it?
The constructor of
DataLink_Layeris trying to call back into theApplication_Layervia aLayer*before theLayerbase class ofApplication_Layeris even constructed (you are still evaluating thenew DataLink_Layer(this)at this time).You can see this more clearly by simply calling
upper->receive()in theDataLink_Layerconstructor.This FAQ explains a little more about using
thisin constructors.This simpler example may more clearly illustrate the issue:
In general, you shouldn’t use the constructor to execute a complicated call stack on partially constructed objects. Just call the
send()orreceive()functions explicitly after construction.