Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

object

class

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...
}
like image 324
Ricky Avatar asked May 12 '15 23:05

Ricky


1 Answers

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
{
    ...
}
like image 104
Levi Avatar answered Nov 15 '22 04:11

Levi