Factory Method C++ – How to delete pointers returned by it

(Last Updated On: November 6, 2016)

Factory method in C++ Interview question description: What approach you will follow to delete pointers returned by Factory method design pattern in C++ in main program? For example, below is given factory method class.

//Factory method design class


Answer: Smart pointer in C++ can be used to delete pointers of object returned by Factory method in C++ in the client code for example in main() method. Smart pointer will handle memory deallocation itself instead of manual call.

Recommended to read this post before moving forward that I have written here how to write Smart Pointer class for a given class in C++.

NOTE: With this interview question, interviewer wants to know if we’re familiar with Smart pointer and what approach we follow to handle memory deallocation for object pointers returned by factory method in C++. Also, they want to know if you can write smart pointer class and familiar about existing auto_ptr or shared_ptr smart pointers in C++ etc. Below, we will see implementation of Smart pointer in C++ and how to use auto_ptr also.

First, let’s have an example of factory method that returns shape object pointers for multiple type of shapes e.g. Circle, Square and Rectangle etc.

getInstance(SHAPETYPE Type)method of ShapesFactory class will return shapes object pointers in below program.


Shape factory that returns multiple type of shapes
If we don’t use smart pointer we have to explicitly call delete on pointers to deallocate memory. For example,
But, if we use smart pointer, delete operation will be handled automatically. Below, we will create a smart pointer class and use it and also, we will use already available smart pointer i.e. auto_ptr.
Example explained with proper comments.