C++ – Copy constructor with pointers


I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor.

To learn that, I have made the following simple code. It compiles, but gives me runtime error when performing the copy constructor.

I am trying to copy just the value from the pointer of the copied object, but avoiding assigning the same address.

So, what's wrong here?

    class TRY{
        TRY(TRY const &);

        int *pointer;

        void setPointer(int);

    void TRY::setPointer(int a){
        *pointer = a;




    TRY::TRY(TRY const & copyTRY){
        int a = *copyTRY.pointer;
        *pointer = a;

    int main(){

        TRY a;

        TRY b = a;


        cout << "Address of object a = " << &a << endl;
        cout << "Address of object b = " << &b << endl;

        cout << "Address of a.pointer = " << a.pointer << endl;
        cout << "Address of b.pointer = " << b.pointer << endl;

        cout << "Value in a.pointer = " << *a.pointer << endl;
        cout << "Value in b.pointer = " << *b.pointer << endl;

        return 0;

I'll be using this concept for other classes with lots of pointers in it, where I need to copy all values from on object to the other. Copying is initially necessary for this code, so I would like to keep the copying possibility (I won't be hiding the copy constructor as private).

Besides, the real class I need to implement has like 10 pointers, and it might be changing with time. Isn't there a somewhat smarter way to have a deep copy constructor in C++?…

Best Answer

With the statement int* pointer you have just defined a pointer but has not allocated any memory. First you should make it point to a proper memory location by allocating some memory like this: int* pointer = new int. Then in the copy constructor again you have to allocate the memory for the copied object. Also, don't forget to release the memory using delete in the destructor.

I hope this example helps:

class B

    B(const B& b);
    void setVal(int val);

    int* m_p;

    //Allocate the memory to hold an int
    m_p = new int;

    *m_p = 0;

B::B(const B& b)
    //Allocate the memory first
    m_p = new int;

    //Then copy the value from the passed object
    *m_p = *b.m_p;


    //Release the memory allocated
    delete m_p;
    m_p = NULL;

void B::setVal(int val)
    *m_p = val;
Related Topic