Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I implement the Factory Method pattern in C++ without using new?

I'm working in an embedded environment (Arduino/AVR ATMega328) and want to implement the Factory Method pattern in C++. However, the compiler I'm using (avr-gcc) doesn't support the new keyword. Is there a way of implementing this pattern without using new?

like image 420
Matthew Murdoch Avatar asked Jun 23 '09 08:06

Matthew Murdoch


People also ask

When would you implement a factory method pattern?

The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.

Which statements indicate the need to use the Factory Pattern?

The Factory Method pattern is generally used in the following situations: A class cannot anticipate the type of objects it needs to create beforehand. A class requires its subclasses to specify the objects it creates. You want to localize the logic to instantiate a complex object.

Is a factory or a template to create new objects of same type?

Factory is a creational design pattern which is used to create different implementation objects of the same type.


1 Answers

Since the AVR compiler is based on the gcc compiler, it is very likely to support the new keyword. What exactly is the error you're getting. I'm guessing it's a link/compiler error along the lines of an undefined function, namely, operator new. There is a difference between the new operator and operator new, the first is used to create objects and the latter is used to allocate memory for objects. The new operator calls operator new for the type of object being created, then initialises the object's v-table and calls the object's constructors. Reading this FAQ it says that operator new is not defined in the standard libraries. This is easy to fix, just define one:

void *operator new (size_t size)
{
  return some allocated memory big enough to hold size bytes
}

and you'll need to define a delete as well:

void operator delete (void *memory)
{
   free the memory
}

The only thing to add is the memory management, the allocation and freeing of blocks of memory. This can be done trivially, being careful not to clobber any existing allocated memory (the code, static / global data, the stack). You should have two symbols defined - one for the start of free memory and one for the end of the free memory. You can dynamically allocate and free any chunk of memory in this region. You will need to manage this memory yourself.

like image 72
Skizz Avatar answered Sep 27 '22 16:09

Skizz