Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set array of object to null in C++

Suppose I have an array of objects of type Foo in C++:

Foo array[10];

In Java, I can set an object in this array to null simply by:

array[0] = null //the first one

How can I do this in C++?

like image 865
Chin Avatar asked Oct 29 '12 01:10

Chin


2 Answers

Use pointers instead:

Foo *array[10];

// Dynamically allocate the memory for the element in `array[0]`
array[0] = new Foo();
array[1] = new Foo();

...

// Make sure you free the memory before setting 
// the array element to point to null
delete array[1]; 
delete array[0]; 

// Set the pointer in `array[0]` to point to nullptr
array[1] = nullptr;
array[0] = nullptr;

// Note the above frees the memory allocated for the first element then
// sets its pointer to nullptr. You'll have to do this for the rest of the array
// if you want to set the entire array to nullptr.

Note that you need to consider memory management in C++ because unlike Java, it does not have a Garbage Collector that will automatically clean up memory for you when you set a reference to nullptr. Also, nullptr is the modern and proper C++ way to do it, as rather than always is a pointer type rather than just zero.

like image 93
sampson-chen Avatar answered Oct 06 '22 00:10

sampson-chen


So, forget Java here, it's not helping you. Ask yourself; what does it mean for an object to be null? Can an object be null? The answer is no, an object can not be null, but a reference (pointer in C++ terms) to one can be.

In java you have reference types, which are similar to pointers under the hood. However, you cannot set objects to null even in java, only references.

In C++ you have fully fledged objects and pointers and references to objects. A pointer to an object (or primitive type) can be null, but an object itself cannot.

So, when you create an array of Foo objects you have, well, an array of Foo objects. You don't have pointers, you have objects. If your array were an array of pointers to objects then yes, you could initialize them to null (nullptr in C++0x), i.e., they don't refer to a valid object.

like image 26
Ed S. Avatar answered Oct 05 '22 23:10

Ed S.