Click here to Skip to main content
15,893,564 members
Articles / Programming Languages / C++

RAII, Dynamic Objects, and Factories in C++

Rate me:
Please Sign up or sign in to vote.
4.71/5 (38 votes)
3 May 200511 min read 411.5K   777   72  
RAII: automatic resource management in C++.
#ifndef MY_HIERARCHY_H
#define MY_HIERARCHY_H

/**
 * This example code is a supplement to the article 
 * 'RAII, Dynamic Objects, and Factories in C++'
 * at CodeProject: http://www.codeproject.com/
 */

#include "raiifactoryimp.h"


/**
 *  A simple base class
 */
class MyBase {
public:
   MyBase() : mi(0) {}
   MyBase (int i) : mi(i) {}
   virtual ~MyBase() {}   // virtual!!

   void set (int i) { mi = i; }
   int  get () { return mi; }
private:
   int mi;
   // non-copyable
  MyBase (const MyBase&);
  MyBase& operator= (const MyBase&);
};


/**
 *  A simple class derived from MyBase
 */
class MyDerived : public MyBase {
public:
   MyDerived() : mi(0), mf(0.0)      {}
   MyDerived (int i): mi(i), mf(0.0) {}
   virtual ~MyDerived() {}

   void set (int i) { mi = i; }
   int  get () { return mi; }
private:
   int mi;
   float mf;
   // non-copyable
  MyDerived (const MyDerived&);
  MyDerived& operator= (const MyDerived&);
};



/**
 * RAII Factory that creates MyBase objects and objects
 * derived from MyBase (e.g. MyDerived) 
 */
class MyPolymorphicFactory  {
public:
   template <typename T>
	MyBase* create() { return imp.keep (new T); }

   template <typename T>
	MyBase* create (int arg) { return imp.keep (new T (arg)); }
private:
   RaiiFactoryImp<MyBase> imp;
};


#endif

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Austria Austria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions