Click to See Complete Forum and Search --> : Object pointer member variables


benbenben
February 21st, 2003, 05:49 AM
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;
}

PaulWendt
February 21st, 2003, 06:24 AM
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.

benbenben
February 21st, 2003, 10:50 PM
Thanks Paul,

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

Regards
Ben