c++ - "new operator" to instantiate another class as a factory? -
i try use new operator instantiate specific class , not 1 behind new keyword.
i try have kind of "factory" abstract class.
it seems me not possible, lets double check ! code compile, main code treat test (and not 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 = 15; }; void* test::operator new(size_t sz) { return ::new testimpl(); } void main() { test * t = new test(); // call new operator, correctly int = test->testcall(); // == 0 , not 15 }
note every new expression, 2 following things performed:
- allocate memory via appropriate
operator new. - construct object on memory allocated step#1.
so operator new allocates memory, doesn't construct object. means, test * t = new test();, still test constructed, on memory allocated overloaded operator new; constructed testimpl inside operator new, it'll overwritten on same memory soon, after operator new finished.
Comments
Post a Comment