1

I have done overloading for new, I'm shocked to see how come my Dev CPP compiler didn't give any error when I have assigned a void * to A *. I'm wondering whether the compiler is doing the required things here, Am I right ?. Thanks in advance.

class A {
public:
    void* operator new(size_t size)
    {           
        return malloc(size);
    }

};


int main(int argc, char** argv) {

    A* a = new A();

    void* v = NULL;

    return 0 ;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Raju
  • 1,149
  • 1
  • 6
  • 19

3 Answers3

4

new is special. Overloading operator new is used to provide storage space from a custom location. But that's only half the job : the object still needs to be constructed in this storage, and that's the compiler job.

When you return storage space, there's no constructed object yet, so it does make sense to return void*. But there's another, compiler-generated step to the A*.

Quentin
  • 62,093
  • 7
  • 131
  • 191
2

operator new must return void* by definition. If you try to make it return int*, then you will get a compilation error.

I think what confuses you is how this void* is turned into an int* without the seemingly required cast. But the point is that this is not a normal conversion, like an attempt to do void* v; int* i = v; in your own code. Such an attempt would indeed fail. The rules for your own code are different from what the compiler is allowed to do.

One such compiler privilege is turning turning the void* from your operator into an int* (or into any T*, that is).

And if you think about, the compiler does even more things behind the scenes when it processes your new expression in A* a = new A();. For example, it will also create an "invisible" constructor call.


P.S.: Dev-C++ is not a compiler, it's an IDE bundled with an old version of GCC. I recommend using a modern compiler.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
-1

As answered in Why does C++ require a cast for malloc() but C doesn't?, conversion from void * to any pointer type without cast is valid in C and not in C++, where a static_cast is required.

Community
  • 1
  • 1
serge-sans-paille
  • 2,109
  • 11
  • 9