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 ?

Recommended Answers

All 5 Replies

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

like :

A()
{
    mem_ptr = 0;
}

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.

Thanks a lot, Guys for all the comments and help.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.