Search code examples
c++classpointersdelete-operator

How delete a pointer of classes which has pointer members?


I mean, if i have some class like:

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

when i call delete pa, will pi be deleted?


Solution

  • 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;
    };