How to instantiate a static object using a non-static variable?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • codingjunkie
    New Member
    • Feb 2008
    • 1

    How to instantiate a static object using a non-static variable?

    Hi,

    I wanted to to do the following and was wondering if that is the correct way-


    // I need to create an instance of another class XYZClass using the member variable m_xyz. The instance ob would be used and modified by the member functions func1, func2, func3 etc of MyClass, but I need the value of ob to persist between function calls. Could you please tell me the correct way to go about this?

    [code=cpp]
    static XYZClass ob(m_abc);

    Class MyClass
    {

    private:

    const char* m_abc;


    public:
    MyClass(const char * abc)
    {
    m_abc = abc;
    }

    int init();
    int func1();
    int func2();
    int func3();
    int exit();

    }


    }[/code]
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by codingjunkie
    // I need to create an instance of another class XYZClass using the member variable m_xyz. The instance ob would be used and modified by the member functions func1, func2, func3 etc of MyClass, but I need the value of ob to persist between function calls. Could you please tell me the correct way to go about this?
    When post code please use code tags (which I have now added) you may wish to read our posting guidelines

    A static instance of XYZClass is not what you need, global data is bad (in fact it always has been even in C) and should be avoided.

    What you need is to have you XYZClass instance contained in your ABCCLass. Either declare a member variable of type XYZClass in ABCClass and instantiate it when ABCClass is constructed or declare a member variable of type XYZClass * and at the point where you need to use it and m_xyz (or is it m_abc) has be initialised 'new' an instance of the XYZClass, not forgetting to delete it once you are done with it or as ABCCLass gets destroyed.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      I have just found and removed your other post, double posting questions is absolutely against our posting guidelines. Please don't do it you could find yourself with a site ban.

      If you think you question has been ignored then you could try posting a reply to it to move it up the forum list. However all moderators have access to a list of unanswered questions you need to be patient. In this case you only waited about 6 hours. This is a multinational forum, if the person answering your question happens to be on the other side of the world it could easily take 18 hours+ for you to get a reply.

      Banfa
      Administrator

      Comment

      Working...