Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"new operator" to instantiate another class as a factory?

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
}
like image 245
CDZ Avatar asked Jul 28 '17 14:07

CDZ


People also ask

What is :: operator new?

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.

Why do we use the new operator when instantiating an object?

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.

What is the difference between new operator and operator new?

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.

What is new operator with example?

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.


1 Answers

Note that for every new expression, the two following things will be performed:

  1. allocate memory via appropriate operator new.
  2. construct the object on the memory allocated by step#1.

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.

like image 66
songyuanyao Avatar answered Oct 06 '22 12:10

songyuanyao