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 C开发者_如何学编程onstructor \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;
}
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.
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
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.
Just a idea, try calling it like this:
foo* objTwo(objOne);
The copy constructor takes a reference to a const object as parameter.
You have the wrong signature for a copy constructor...
It can't be a pointer....
foo( const foo &obj )
精彩评论