You can't really add a new member at runtime - C++ is statically typed and therefore everything about a type must be specified at compile time.
You can simulate adding a new 'member' at runtime, though:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <boost/any.hpp>
#include <map>
struct A
{
template< typename T >
void add_member( const std::string& name, const T& value )
{ member[name] = value ; }
template< typename T >
T get_member( const std::string& name )
{ return boost::any_cast<T>( member[name] ) ; }
// map member name to variable
std::map< std::string, boost::any > member ;
};
And now:
1 2 3 4 5 6 7 8 9 10 11 12
A a ;
a.add_member( "count", 203 ) ;
a.add_member( "id", std::string("A1004") ) ;
try
{
std::cout << "count: " << a.get_member<int>("count") << '\n' ;
}
catch( const boost::bad_any_cast& )
{
std::cerr << "no member of type 'int' with name 'count'\n" ;
}
// etc...
Why can't you add members dynamically? Just create a dynamic container for members, and then if you need a new member, make a new member in the container.
You may be able to use the Prototype Design Pattern for what you are asking. As JLBorges has already pointed out C++ is statically typed language. The Prototype pattern is the key to exploiting such facilities in a language like C++.