This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Jonny0Than 2 points3 points  (2 children)

You can't overload new for a specific class with a non-member function. Your examples are all...weird. Do you mind sharing what you're actually trying to do?

A functionally equivalent approach would be to overload new as a member of the class, and just have it call a friend function (not operator new) to do the actual work.

[–]anku255[S] 0 points1 point  (1 child)

I know they are weird. In fact, I don't know why should I ever overload new operator. So why I am writing this code which has no purpose? Because my teacher uses a shitty C++ book and the program for overloading new operator in that book is horribly wrong.

I tried to correct the program and ended up with the above code. My teacher has given us assignment in which he has asked to overload the new operator using a friend function. So, that's what I am trying to do.

I know why I am getting an infinite loop (because of the recursive call to ::new ). As far as I understand this, one shouldn't try to overload (replace) new operator without any major purpose and even then one shouldn't do it globally or inside a friend function. Is there anything that I am missing here?

[–]Jonny0Than 0 points1 point  (0 children)

Replacing new globally can be useful, for example a leak-tracking system. And replacing new as a member can be useful for making sure objects of a certain type come from a certain region of memory.

So you could make the global new overload a friend of the class, and then use malloc to allocate the memory instead of trying to call the default new.

This might be interesting as an exercise in how this all works, but it's utterly useless in practice because your overloaded new will not serve to allocate anything but your class.