I am an intermediate java programmer and I am used to relaying on the null value in java for cheking if objets are initialized with some reference to instanced object in memory. I want to do something similar in c++ but I do not have a clear idea about how I can achieve it. I want to initialize a user array – user is a class I have defined – so I can check if the actual position in the array does contain an object or it is free.
I have tried to use the null definition in c++ but found out that it is simply a “-1” int value and I could not use it properly. So basically I need something to distinguish between a free position in my array and an ocuppied one.
Additionally I might be interested in having an extra value to distinguish a position that contained a removed user, since I am planning to just mark the desired position with a special mark as a freed position when it comes to the method that remove a user from the array.
For the curious ones, I am implementing a simple hash set and the remove method in my class just mark the position of the element to remove instead of doing some restruction.
I think there are some concept you need to understand.
Unlike Java, when you are creating an N-element array of User, it is NOT an array of reference. It is really a piece of memory containing actual N user, which is already created and initialized (i.e. constructor already run). (Well, there are more advanced topics like placement-new but I think it is not really what you are looking for yet)
So it is somehow contradicting if you said you have an “array of User” and want to keep track if certain position is initialized.
Unless:
You are not creating array of User, but Array of “Pointer to User” (or other reference like auto_ptr). By such way, it is meaningful to say certain element is “null”; or
Your “initialize” do not mean creating an object instance, but an explicit initialization action (like executing an init() method of an User instance). By such way, it is meaningful to say certain element is “not initialized”.
(First of all, as you are writing C++, I shall recommend you to use std::vector, not array. However I am using array in this answer, as to stick close to your question)
For case 1, it is strict forward, simply use NULL (avoid using 0, because, although NULL is defined as 0 in most system, using NULL actually makes the code more readable and more portable):
For case 2, you have many other choice, like keeping another array of boolean to keep the “initialized” flag, or have a wrapper over User for such extra flag, or simply add such flag into your User class, etc.
e.g.
(honestly I think case 2 is not really what you are looking for)