-4

Lets say we have this..

class MyClass
{
    int value;

    void addIntToObject(int num)
    {
        value = num;
    }

}


MyClass *object = new MyClass();
object->addIntToObject(1);
object->addIntToObject(2);

Now let's say we do this again...

object = new MyClass();

By using new twice on the same object, does that mean we have deleted all data that was stored in object? can someone explain to me the exact workings of using new twice on the same object

Would this be an efficient way to free memory? (like using delete and delete[])

dlmeetei
  • 7,297
  • 3
  • 25
  • 34

2 Answers2

8

You didn't "do new twice on the same object". The new expression creates an object. By doing new twice you made two entirely separate objects.

The variable object is a pointer. It points to other objects. The = operator on a pointer means to change which object the pointer is pointing to.

So in your code there are two objects, and you change object (the pointer) to point to the second object. The first object still exists but nobody knows where it is, this is known as a memory leak.

M.M
  • 130,300
  • 18
  • 171
  • 314
0

The thing on left side of = is a pointer i.e to be simple it can contain adrress of some memory location/object instance

When you do new MyClass() -> each execution of this statement will produce a new instance/object/memory of MyClass

So when you do this first time,

MyClass *object1 = new MyClass(); 
// here object1 now holds the address of object
created by executing 'new MyClass()' suppose that address is 1

Now create a object again,

object1 = new MyClass(); 
//here object1 now holds the address of object
created by again executing 'new MyClass()' suppose that address is 2

In the end both objects remain in memory i.e 1 as well 2. So nothing is deleted.

The pointer(left side of =) was first pointing to object with adrress 1. Now, it pointing to object with adress 2.

JTeam
  • 1,206
  • 9
  • 13