Feb 052013
 

Object of a class can be created dynamically on heap or statically on Stack or Data Area. If we have a class MyClass, then the below objects will be created on heap.

// Operator: New
MyClass *ptr1 = new MyClass(); // Crating object of MyClass on heap.

// Operator: New-Array
MyClass *ptr2 = new MyClass[10]; // Create an array of object MyClass on heap.

However, objects can also be created statically as below:

// Global object created at load time in the data area
MyClass obj1;

void func()
{
    // Object getting created on the Stack 
    // (Activation record of function func).
    MyClass obj2;

    // Global object created at load time in the data area
    static MyClass obj3;
}

Design a class which does not allow any object to be created on heap.
Continue reading »

Jun 132012
 

How will you handle a situation if new operator is not able to allocate memory on heap to your program?

In C language malloc returns NULL, if it is not able to allocate memory, so the check can be as below:

    int *ptr = malloc(sizeof(int));
    if (ptr == NULL)
        ;    // malloc not able to allocate memory on heap

The reason for not being able to allocate memory may be because there is no space in the heap or anything. So how do we check for out-of-memory conditions for new operator?

Just to mention that malloc is a function and new is an operator, however it can be overloaded as a function. Continue reading »