Search code examples
c++new-operatoroverload-resolution

Overload resolution of operator new regarding nested classes


If I overload operators new and delete for a class with a nested class:

class A
{
public:
    static void* operator new(size_t);
    static void operator delete(void*);

    class B;
}

Will allocations for instances of A::B objects and allocations within A::B objects use the overloaded A::new and A::delete or the global defaults?


Solution

  • First of all, chances are very high that you do not need to overload new nor delete and should avoid doing so.

    Baring that, the overloaded operators are going to apply to class A, not to class A::B. If you wanted to have B with overloaded operators, you would need to overload them in class B as well.

    For an example of how to overload new and delete: http://www.cprogramming.com/tutorial/operator_new.html