|
-
February 21st, 2003, 06:49 AM
#1
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;
}
-
February 21st, 2003, 07:24 AM
#2
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.
-
February 21st, 2003, 11:50 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|