Mahesh
Mahesh

Reputation: 34615

Copy constructor not called !

I don't understand why in this case copy constructor isn't called. Can some one please explain ?

#include <iostream>

class foo
{
    int* ptr;
    public:
    foo()
    {
        std::cout << "\n Constructor \n" ;
        ptr  = new int;
        *ptr = 10;
    }

    foo( const foo* &obj )  // Copy Constructor
    {
         std::cout << "\n Copy Constructor \n" ;
         ptr  = new int;
         *(this->ptr) = *(obj->ptr);
    }

    // Copy Assignment Operator

    ~foo()  // Destructor
    {
        delete ptr;
    }
};

int main()
{
    foo* objOne = new foo;
    foo* objTwo = objOne ;

    getchar();
    return 0;
}

Upvotes: 1

Views: 787

Answers (6)

paxdiablo
paxdiablo

Reputation: 881133

Because you're just creating another pointer to the same object, not a new object:

foo* objOne = new foo;
foo* objTwo = objOne;
   ^
   |
   +-- these are pointers.

If you want a new object, use something like:

foo objTwo = objOne;

and fix your copy constructor:

foo (const foo &obj) ...

The following snippet shows one way to do it:

#include <iostream>

class foo {
    public:

    foo () {
        std::cout << "constructor" << std::endl;
        ptr  = new int;
        *ptr = 10;
    }

    foo (const foo &obj) {
        std::cout << "copy constructor" << std::endl;
        ptr  = new int;
        *(this->ptr) = *(obj.ptr);
    }

    ~foo () {
        delete ptr;
    }

    private:

    int* ptr;
};

int main()
{
    foo objOne;
    foo objTwo = objOne ;
    return 0;
}

And this outputs:

constructor
copy constructor

as you would expect.

Upvotes: 9

Yochai Timmer
Yochai Timmer

Reputation: 49221

You have the wrong signature for a copy constructor...

It can't be a pointer....

foo( const foo &obj )

Upvotes: 0

James
James

Reputation: 8586

You're copying a POINTER to an object, not the object. Hence no copy constructor call - you're just assigning objTwo to be the same address as objOne.

Upvotes: 2

Didier Trosset
Didier Trosset

Reputation: 37427

The copy constructor takes a reference to a const object as parameter.

Upvotes: 0

Nordic Mainframe
Nordic Mainframe

Reputation: 28737

 foo( const foo* &obj )

is not the copy constructor

 foo( const foo &obj )

is

Also, you are copying object pointers, not objects. You can't define a copy constructor for object pointers. The usual solution in C++ is to create a smart pointer class which wraps the pointer. See:

http://en.wikipedia.org/wiki/Smart_pointer

Upvotes: 3

Oralet
Oralet

Reputation: 347

Just a idea, try calling it like this:

foo* objTwo(objOne);

Upvotes: 0

Related Questions