Why do we don't need to type-cast when we use new operator
Hi,
I am writing a sample code like this
#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;
class C {
public:
C();
void* operator new (size_t size); //implicitly declared as a static member function
void operator delete (void *p); //implicitly declared as a static member function
};
void* C::operator new (size_t size) throw (const char *){
void * p = malloc(size);
if (p == 0) throw "allocation failure"; //instead of std::bad_alloc
return p;
}
void C::operator delete (void *p){
C* pc = static_cast<C*>(p);
free(p);
}
int main() {
C *p = new C; // calls C::new
delete p; // calls C::delete
}
Here while using the new operator or inside the new operator function, i have not mentioned any type casting to type 'C', more over i am returning a void pointer inside the operator function, in this case how the compiler is ablt to match it properly ?
Is it the C++ compiler(language) technique /Is it the new operator technique ?
Re: Why do we don't need to type-cast when we use new operator
As another recent thread pointed out, operator new is not actually the same as the new keyword. Operator new, which is overloadable, only controls the memory-allocation portion; the constructor is then called on the allocated memory by the new keyword, and that part you can't overload.
So there's a step between the return from operator new and the return from the new keyword which is invisible to you, in which that void* is converted to a C* by the call of a constructor.
Likewise, the destructor is called before operator delete, so it is incorrect to static_cast p to a C* in that case; the C* no longer exists, just blank memory.
Re: Why do we don't need to type-cast when we use new operator
Can you also explain me about how the compiler able to allocate the required memory even though we are not using the sizeof function in case of new operator
ex:
SampleClass *sm = new SampleClass() // here i didn't used the szieof
Re: Why do we don't need to type-cast when we use new operator
Quote:
Originally Posted by rsodimbakam
Can you also explain me about how the compiler able to allocate the required memory even though we are not using the sizeof function in case of new operator
ex:
SampleClass *sm = new SampleClass() // here i didn't used the szieof
You seem to ask a lot of questions as to why C++ is the way it is.
The creator of the C++ language wanted C++ to be a "safer" 'C', where type need not be known in many instances.
But here is the bottom line -- Every computer language has rules and syntax -- continually questioning why a language is allowed (or not allowed) to do something is really pointless.
At some point, you need to realize that C++ syntax is the way it is, and just learn how to program using the language.
Regards,
Paul McKenzie
Re: Why do we don't need to type-cast when we use new operator
maybe the OP's name is just a synonym for george2?