Dinar Abdullin
Dinar Abdullin

Reputation: 165

Initialize an dynamically allocated object by already existing object

How can I assign an dynamically allocated object by already existing object(the same class object) without changing the latter one. Code, which seems does not work:

ClassName<T> Object1(parameters);
...
ClassName<T>* pObject2 = new ClassName<T>(parameters);
pObject2 = &Object1;
...some operations on pObject2
delete pObject2

Upvotes: 1

Views: 191

Answers (4)

Jan Hudec
Jan Hudec

Reputation: 76246

You are assigning the pointer. You need to assign the content:

*pObject2 = Object1;

pObject2 is a pointer. If you assign it you are making it to point to Object1, forgetting the pointer to the dynamically created instance in the process.

Instead you need to assign the instance, *pObject2. That will invoke ClassName<T>::operator=, which is either autogenerated to assign all members, or hopefully manually written to do whatever else is the right thing for the type.


Edit: Of course, as Guido Kanschat realized in the other question, while this is what was wrong with your attempt, you should really use the copy constructor directly. Why initialize the second object with arbitrary junk when you are going to reinitialize it with object1 anyway.

Upvotes: 1

jsidhu
jsidhu

Reputation: 91

Like others have said you should use define a copy constructor, or overload the assignment operator. Then, all you need to do is the following:

ClassName<T>* pObject2 = new ClassName<T>(Object1);

or,

ClassName<T>* pObject2 = new ClassName<T>(parameters);
*pObject2 = Object1;

Of course, to ensure you will not modify the original, you may want to read up on deep copy vs. shallow copy.

Upvotes: 1

Guido Kanschat
Guido Kanschat

Reputation: 191

Assuming you have a copy constructor:

ClassName<T>* pObject2 = new ClassName<T>(Object1);

In your code snippet, you first assign values to Object2, which are discarded right away. Furthermore, you even overwrite the pointer itself, thus creating a memory leak, by assigning it the address of Object1 instead of assigning its contents to the memory pointed to.

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409166

What you are doing is not copying from Object1 to what pObject2 points to, instead you just make the pointer pObject2 point to Object1, thereby loosing the memory you allocated.

This will lead to you trying to free memory you haven't allocated when you delete the pointer, which is undefined behavior and most likely will cause a crash.

What you want to do is to use the dereference operator * on the pointer pObject2, to get the object that the pointer points to, and assign to that object instead:

*pObject2 = Object1;

Or use the copy-constructor of the class when allocating:

ClassName<T>* pObject2 = new ClassName<T>(Object1);

Upvotes: 2

Related Questions