Factory is implemented as an independent class with a static member function called create(). create() returns a pointer whose static type is that of the abstract base class. The dynamic typeof the returned pointer will reflect the actual object that has been created for viewing the image:
static Image* create(const std::string& ext)
return new JpgImage;
else if (ext=="bmp")
return new BmpIamge;
return new PngImage;
Technically, you don't need to instantiate an ImageFactory object to call create() because it's a static member function. However, for the sake of an intuitive and cleaner syntax, you can still create a factory object, as shown in the following code listing. Additionally, it's best to use a smart pointer to ensure automatic cleanup of object created by the factory class. Smart pointers such as std::tr1::shared_ptr, std::auto_ptr, and its successor, std::unique_ptr, also offer the convenience of the member function reset()which disposes of an image object and binds a new object to the same smart pointer in one shot:
std::auto_ptr<const Image> img(factory.create("jpg"));
img->image_type(); //output: "jpg image"
img->image_type();//output: "bmp image"
img->image_type(); //output: "png image"