Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: new

📅 2010-Nov-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

In C++, the new expression is used to create an object on the heap. For example:

class Foo
{
public:
    Foo()
    {
        cout << "Constructor";
    }
};

int main()
{
    Foo* f = new Foo(); // new
    return 0;
}

What actually happens when a new expression new Foo() is executed is:

  1. The default operator new function is called. This function merely allocates enough memory to hold an object of Foo. It returns a void* pointer to this memory.

  2. The constructor of Foo is called to initialize the object memory obtained from the above step.

The confusing part here is the difference between the new expression and the operator new function. The new expression is a part of the language, it cannot be modified. It behaves as described above.

The operator new has a default implementation in the standard library. But, it can also be overloaded for a class. For example:

#include <iostream>
using namespace std;

class Foo
{
public:
    Foo()
    {
        cout << "Foo constructor" << endl;
    }

    void* operator new( size_t i )
    {
        cout << "operator new" << endl;
        return malloc( i * sizeof( Foo ) ); // Allocate raw memory
    }
};

int main()
{
    Foo* f = new Foo();
    return 0;
}

Executing the new expression new Foo() first results in a call to Foo::operator new() and consequently to the Foo constructor. The operator new function has a fixed function signature. The first parameter is always a size_t and it returns a void* pointer to the allocated memory. Overloading the operator new function is how a custom allocator is provided for a class.