8.2. Using a Function to Create Objects (a.k.a. Factory Pattern)

Problem

Instead of creating a heap object with new, you need a function (member or standalone) to do the creation for you so that the type of the object being created is decided dynamically. This sort of behavior is what the Abstract Factory design pattern achieves.

Solution

You have a couple of choices here. You can:

  • Have the function create an instance of the object on the heap, and return a pointer to the object (or update a pointer that was passed in with the new object’s address)

  • Have the function create and return a temporary object

Example 8-2 shows how to do both of these. The Session class in the example could be any class that you don’t want application code to create directly (i.e., with new), but rather you want creation managed by some other class; in this example, the managing class is SessionFactory.

Example 8-2. Functions that create objects

#include <iostream> class Session {}; class SessionFactory { public: Session Create(); Session* CreatePtr(); void Create(Session*& p); // ... }; // Return a copy of a stack object Session SessionFactory::Create() { Session s; return(s); } // Return a pointer to a heap object Session* SessionFactory::CreatePtr() { return(new Session()); } // Update the caller's pointer with the address // of a new object void SessionFactory::Create(Session*& p) { p = new Session(); } static SessionFactory f; // The one factory object int main() { Session* p1; Session* p2 = new Session(); ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.