6

I mean, if i have some class like:

class A{
    int* pi;
};
*A pa;

when i call delete pa, will pi be deleted?

3
  • It will be if you code it to be. It won't be if you code it not to be. Decide which you want and code that. Commented Feb 29, 2012 at 11:43
  • Avoid this with standard library containers or smart pointers as members. Commented Feb 29, 2012 at 11:59
  • No. But note it will call the destructor where you can do clean up of the A instance. If you want to delete pi there then you can do that. BUT you must make sure you correctly own the pointer first. Loop up rule of three. Commented Feb 29, 2012 at 15:36

3 Answers 3

12

You need to define a destructor to delete pi;. In addition you also need to define a copy constructor and assignment operator otherwise when an instance of A is copied two objects will be pointing to the same int, which will be deleted when one of the instances of A is destructed leaving the other instance of A with a dangling pointer.

For example:

class A
{
public:
    // Constructor.
    A(int a_value) : pi(new int(a_value)) {}

    // Destructor.
    ~A() { delete pi; }

    // Copy constructor.
    A(const A& a_in): pi(new int(*a_in.pi)) {}

    // Assignment operator.
    A& operator=(const A& a_in)
    {
        if (this != &a_in)
        {
            *pi = *a_in.pi;
        }
        return *this;
    }
private:
    int* pi;
};
Sign up to request clarification or add additional context in comments.

Comments

1

You should implement a destructor, ~A(), that takes care of cleaning up A's stuff. Afterwards, calling delete on a pointer of type A will clean-up everything.

1 Comment

But always remember that, if you need a destructor, you almost certainly need a copy constructor and copy-assignment operator too, per the Rule of Three
1

You will need to write a destructor to delete all pointer type members. Something like:

class A
{
    int *pi;
  public:
    ~A(){delete pi;}
};

You will need to ensure that your constructor assigns a value to pi( at least a NULL). and like the answer from @hmjd, you will need to implement or hide the copy constructor and assignment operators. Look for the rule of three here: http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.