CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2003
    Posts
    4

    Question Object pointer member variables

    Hi,

    I have two classes CA and CB, CA stores the object pointer of CB.
    When Hello() is called object pointer of CB is stored in m_pObjB.

    When scope of Hello() ceases, destructor of CA is invoked, which deletes m_pObjB. But this results in pObjB getting invalid.

    Now if m_pObjB is not deleted in destructor of CA, there will be memory leak.

    All I need is to store *CB in CA. But the *CB comes from outside CA(ie via the constructor).
    I would be glad if someone can throw light on this.

    Thanks in Advance
    Regards
    Ben


    Following is the code snippet:

    class CB;
    class CA
    {
    public:

    CA(CB* pObjB)
    {
    m_pObjB = pObjB;
    }

    CA();
    virtual ~CA()
    {
    if(m_pObjB)
    {
    delete m_pObjB;
    m_pObjB = NULL;
    }
    }

    private:
    CB* m_pObjB;
    };

    class CB
    {
    public:
    void Hello()
    {
    CA aObj(this);
    }

    CB();
    virtual ~CB();

    };

    int main()
    {
    CB* pObjB = NULL;

    pObjB = new CB;

    pObjB->Hello();

    delete pObjB;

    return 1;
    }

  2. #2
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    If you look at what you're doing, you're deleting B's pointer twice.
    If A takes "ownership" of the pointer passed into it, then you can't
    delete the pointer external to A; let A take care of it.

    Additionally, the way you have things designed, A would be
    considered a "parent" class. You shouldn't have child objects
    create their own parents. You should create A at the same scope
    you're creating B.

  3. #3
    Join Date
    Feb 2003
    Posts
    4
    Thanks Paul,

    As you said, this is more of a design problem than a problem with pointers.

    Regards
    Ben

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured