Hi ,

Sorry for this basic question, i am stuck, with somethings,

I have a class

class A{

int * mem_ptr;

}


then somewhere in the code:

if ( mem_ptr == NULL )
{
mem_ptr = new int;
}

Is it safe to assume that mem_ptr is NULL when the class A object is created ?

no its not safe it can be any value..
its better to initialize mem_ptr to 0 in the constructor of your class.

It is never safe to "AssUMe" anything, you know what that does (and no, I don't expect everyone to get that joke).

When your class A is instantiated, it is currently instantiated with a "dangling pointer". It is your responsibility to initialize it to NULL in your constructor.

Also, because it is a class you can't access the member from external code anyway. You haven't specified an access level so it defaults to private.

This is a better way:

class A {
 private:
   int *mem_ptr;
 public:
   A() : mem_ptr(NULL) {}
};

This GUARANTEES that mem_ptr is NULL. However it does not allow you to modify it from external code. You will have to add a public member function, and a proper delete statement or a destructor, to do it correctly.

Edited 6 Years Ago by Fbody: n/a

Speaking of pointers and NULL, it has to be mentioned there is one thing you can safely assume - you are allowed to delete a pointer that is NULL.

Many people put a check before they delete it, but standard guarantees you can safely perform a delete on a pointer that is NULL.

This article has been dead for over six months. Start a new discussion instead.