I try to use the new
operator to instantiate a specific class and not the one behind the new
keyword.
I try to have a kind of "factory" for an abstract class.
It seems to me that it is not possible, but lets double check !
This code compile, but the main code treat it as a Test
(and not a TestImpl
class)
class Test
{
public:
virtual int testCall() { return 0; };
static void* operator new(std::size_t);
};
class TestImpl : public Test
{
virtual int testCall() override
{
return i;
}
int i = 15;
};
void* Test::operator new(size_t sz)
{
return ::new TestImpl();
}
void main()
{
Test * t = new Test(); // Call the new operator, correctly
int i = test->testCall(); // i == 0 and not 15
}
The new operator invokes the function operator new . For arrays of any type, and for objects that aren't class , struct , or union types, a global function, ::operator new , is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
The difference between the two is that operator new just allocates raw memory, nothing else. The new operator starts by using operator new to allocate memory, but then it invokes the constructor for the right type of object, so the result is a real live object created in that memory.
An Example of allocating array elements using “new” operator is given below: int* myarray = NULL; myarray = new int[10]; Here, new operator allocates 10 continuous elements of type integer to the pointer variable myarray and returns the pointer to the first element of myarray.
Note that for every new expression, the two following things will be performed:
operator new
.So operator new
only allocates memory, doesn't construct the object. That means, for Test * t = new Test();
, still a Test
will be constructed, on the memory allocated by the overloaded operator new
; even you constructed a TestImpl
inside the operator new
, but it'll be overwritten on the same memory soon, after the operator new
finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With