Solution to the Nesting problem in C++