0

having trouble understanding where assignment operator vs copy constructor vs constructor are used in the below cases, help?

Scenario #1

ObjectType newObj = *new ObjectType;

Scenario #2

newObj = theObj;
jjohns
  • 3
  • 1

1 Answers1

0

Scenario #1

ObjectType newObj = *new ObjectType;

using these functions in the following order:
constructor
copy constructor

Scenario #2

newObj = theObj;

using these functions in the following order:
assignment operator

  • Good answer and to the point. I would also like to point out that Scenario 1 is bad, because you allocate an object on the heap without saving the pointer anywhere. That means you have memory loss every time you run that line. – adentinger Apr 07 '17 at 22:23
  • @AnthonyD. can you elaborate on what you mean by that? isn't the pointer being saved in the object "newObj"? – jjohns Apr 07 '17 at 22:28
  • @jjohns Not the pointer. C++ has the concept of pointers as well as values. The *value* is stored in `newObj`, which value was obtained by dereferencing the pointer. However, we don't track the pointer itself. – Justin Apr 07 '17 at 22:29
  • @AnthonyD. i am not sure if I am stating this correctly and please correct me if I am wrong, so what you are saying is that "*new ObjectType" would allocate a new object of type "ObjectType" and would also allocate space in memory for a pointer pointing to that new object. But then the object itself would get another pointer which is being referred to as "newObj" but the original pointer is still there and isnt being referred to by anything? – jjohns Apr 07 '17 at 22:33
  • Any time you `new` but don't `delete` the same object, you have a memory leak. `ObjectType newObj = *new ObjectType;` calls `new` which creates an object, then uses the copy constructor to create a second object, but the first object is lost and never destroyed. You've left yourself with no way to get at the first object in order to properly `delete` it. – aschepler Apr 08 '17 at 00:30