Adding member to an object

Hi all,

in old standard C++ I know that is no way to add a member to an object dynamically? Is there any to do it in the new standard C++11?

That is when you want to add a new member at runtime. Member identifier is hard codeed in this case...
Still not possible and I doubt it will ever be.
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... 


Last edited on
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.
@ciphermagi, that is not strictly a member. A class might have a pointer as a member but what the pointer points to is not a member of the class.
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++.

http://www.oodesign.com/prototype-pattern.html

A good book is here...

http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=sr_1_1?ie=UTF8&qid=1330970919&sr=8-1
> You may be able to use the Prototype Design Pattern for what you are asking.

No. NO.
Topic archived. No new replies allowed.