Tuesday, 17 April 2012

Is there any need for checking of NULL after executing p = new Animal ()? | C++

There is no need for checking of NULL after p = new Animal() because the repetitive use of an explicit NULL after the allocation of new makes the code very monotonous.
Let's understand this concept with the help of the following code:
Animal* p = new Animal();
if (p == Null)
throw Std::bad_alloc();
Moreover, in the absence of the support of the compiler, the code becomes more monotonous.
For example,
Animal* p = new Animal();
if (p == Null)
{
std::cerr<< "Cloud't allocate memory for an Animal" < abort();
}
When the allocation of sizeof(Animal) during p = new Animal()is not done, an exception indicating the bad allocation will be thrown. There should be a simple coding which is:
Animal* p = new Animal(); // The checking of Null is not needed.
In .cpp files, some standard headers must be included in case of failing of throwing an exception by new.

No comments: