Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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(); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page