Edit: Ok, now for an actual code review.
Your design utilises dynamic_cast
in a number of places. You can actually replace all of these in the readLine
function with static_cast<declaration>
since we know that it will not fail here. This will also not incur the performance penalty of having to do the type check.
The memory leak you talk about shouldn't really be something that is an afterthought. In this situation, if you have access to C++11, you should be using RAII to stop memory leaks and to solidify ownership:
#include <memory>
std:unique_ptr<declaration> readLine()
{
//...
}
The main difficulty with this design is, as I've said previously, that the user of this has to know in advance what type you're getting back is. Unfortunately, this is the opposite of the problem that polymorphism is trying to solve. With polymorphism, the idea is that you get back an instance of some class that conforms to an interface, but that you should not care what the underlying type is. In this case, you're returning a base class, but you are required to know what its underlying subclass is. Because of the nature of the problem, and the fact that C++ cannot overload functions by return type, this isn't really the correct way to go: classic OOP won't work here. What is really required is more akin to union
, which has its own problems. Thus the choice of using boost::variant
in the solution above: it can be used in similar situations, but is generally easier and less error prone to work with.
As a final word, this solution itself still isn't perfect. It is still relatively easy for a someone using the above code to forget to do the proper checks to make sure they're casting things to the correct type. Due to the nature of the way the data is stored, this isn't really something that can be worked around in the code that reads it in. The better option would be to modify the data itself: this could be as simple as adding an extra field with the value type or prefacing the value with its type, for example:
max_search_depth integer:10
enable_recursion boolean:false
job_name string:Khalessi
Then, while parsing the file, the type information would be there along with the value. If you are able to modify the file format, this may be the simplest solution.