Search code examples
c++classobject

How do I check if an Object has been initialized/created in C++?


So I have the following class...

class Pet
{
    public:
        Pet() : id(0),
            name("New Pet")
        {

        }

        Pet(const int new_id, const std::string new_name) : id(new_id),
            name(new_name)
        {

        }

        Pet(const Pet new_pet) : id(new_pet.id),
            name(new_pet.name)
        {

        }
    private:
        const int id;
        const std::string name;
};

Somewhere in my code I then create a instance of this class like so...

Pet my_pet = Pet(0, "Henry");

Later on in my code, an event is supposed to cause this pet to be deleted. delete(my_pet);

How do I check if my_pet has been initialized...

Would something like this work?

if(my_pet == NULL)
{
    // Pet doesn't exist...
}

Solution

  • Assuming you mean

    Pet* my_pet = new Pet(0, "Henry");
    

    instead of Pet my_pet = Pet(0, "Henry");
    You can initialise your Pet object to NULL (or nullptr for C++11) like so:

    Pet* pet = NULL; // or nullptr
    

    and later assign it an instance of Pet:

    pet = new Pet(0, "Henry");
    

    This allows you to check the value of pet without invoking undefined behaviour (through uninitialised variables):

    if (pet == NULL) // or nullptr
    {
        ...
    }