C++ Dynamic object construction

Posted by Rajesh Subramanian on Stack Overflow See other posts from Stack Overflow or by Rajesh Subramanian
Published on 2012-04-10T05:12:55Z Indexed on 2012/04/10 5:29 UTC
Read the original article Hit count: 183

Filed under:
|

I have a base class,

class Msg
{

     ParseMsg()
     {
         ParseMsgData();
         ParseTrailer();
     }
     virtual void ParseMsgData() = 0;
     ParseTrailer();

};

and derived classes,

class InitiateMsg
{
    void ParseMsgData() { ... }
};


class ReadOperationMsg
{
    void ParseMsgData() { ... }
};


class WriteOperationMsg
{
    void ParseMsgData() { ... }
};

and the scenario is below,

    void UsageFunction(string data)
    {
      Msg* msg = ParseHeader(data);
      ParseMsg
    }

   Msg* ParseHeader(string data)
   {

        Msg *msg = NULL;
           ....
         switch() 
         {

            case 1: 

                 msg = new InitiateMsg();
                 break;
            case 2:
                 msg = new ReadOperationMsg{();
                 break;
             case 3:
                 msg = new WriteOperationMsg{();
                 break;
               ....

         }

          return msg;           
    }

based on the data ParseHeader method will decide which object has to be created, So I have implemented ParseHeader function outside the class where I am using. How can I make the ParseHeader function inside the Msg class and then use it?

In C# the same is achieved by defining ParseHeader method as static with in class and use it from outside,

© Stack Overflow or respective owner

Related posts about c++

Related posts about inheritance