Search code examples
c++classdata-structuresstructstructure

Can I add member variables to a structure, after i have declared it?


Can I add member variables to a structure, after i have declared it? For example:

struct address 
    { 
       char name[50]; 
       char street[100]; 
    };

Can i dynamically (through code), add another member variable to the structure? Using something like address.addMember(pinCode); if something like this exists!

struct address 
    { 
       char name[50]; 
       char street[100]; 
       int  pinCode;
    };

Solution

  • What you strive to achieve is not possible so bluntly, however it's not impossible!

    One way would be by extending the address by the new members via inheritance.

    struct address 
    { 
       char name[50]; 
       char street[100]; 
    };
    
    struct pin_address : public address 
    { 
       int pinCode;
    };
    

    Other would be by implementing some kind of std::variant - std::map structure which will allow you to dynamically add/remove members.

    #include <variant>
    #include <map>
    
    using Object = std::variant<int,double,std::string>;
    using Members = std::map<std::string,Object>;
    
    struct address
    {
        Members m_members;
    
        address()
        {
            m_members.emplace("name", Object{});
            m_members.emplace("street", Object{});
            m_members.emplace("pinCode", Object{});
        }
    }