Main BLOGGER
Google
WWW THIS BLOG
Monday, November 21, 2005
 
Virtual Construtor in C++
Problem: In message passing environment, Getting the right class instantiated on the receiving end.

Approach:
1. Tag each message class with a unique ID.
2. a global object pool consists of instance of each message class, i.e., each message class will rigister itself to this global object pool with an instance.
3. When getting a message, the tag is looked up and the new object will be created by CLONE (ing)

class Message {
public:
static Message* newMessage( const Message& );
virtual Message* clone() const {
return new Message; // or return new Message( *this );
}
...
};

Message* Message::newMessage( const Message &prototype ) {
return prototype.clone();
}

class myMessage {
public:
virtual Message* clone() const {
return new myMessage; // or return new myMessage( *this );
}
...

All you need to do is create an object of each class in the Message hierarchy and put them in a container class which can be searched. When
you receive a message, get the type ID and iterate on the container of Message objects until you find a match. Use that object as the argument to
newMessage().

void messageHandler( const messageStream &msg )
{
...
msg >> messageType;
Message* prototype = objectContainer.find( messageType );
Message* currentMsg = Message::newMessage( prototype );
msg >> ¤tMsg;
...
}
};



<< Home

Powered by Blogger

Google
WWW THIS BLOG