<<< Copy constructors     Index     Copy constructor example >>>

21. The need for a copy constructor

  • 
    // This program crashes:
    class Terminator {
        int* m_ptr;
    public:
        Terminator( int* ptr )
        {
            m_ptr = ptr;
        }
    
        ~Terminator()
        {
            delete m_ptr;
        }
    };//class Terminator
    
    int main()
    {
        int* ptr = new int;
        *ptr = 12345;
        Terminator alice( ptr );
        Terminator bob = alice;
        return 0;
    }
    
    
  • 
    // Solution:
    class Terminator {
        int* m_ptr;
    public:
        Terminator( int* ptr )
        {
            m_ptr = ptr;
        }
    
        // Copy constructor -- deep copy
        Terminator( Terminator& another )
        {
            m_ptr = new int;
            if ( another.m_ptr ) {
                *m_ptr = *another.m_ptr;
            }
        }
    
        ~Terminator()
        {
            delete m_ptr;
        }
    };//class Terminator
    
    

<<< Copy constructors     Index     Copy constructor example >>>