-2

I'd like to add members to a struct after its definition. Any way I can do something like this?

struct ss {};
ss.name = ""; //add a string member
ss.age = 0; //add an int member
    
cout << ss.name << "," << ss.age;
  • 4
    You can't.That's not how c++ works. Refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Moreover, `struct ss = {};` is **not even valid** c++ syntax. – Jason Aug 19 '22 at 04:43
  • Hmm, and there isn't reflection either -- The plot of how to c++ thickens! Dun dun dunnnn... I just need to be able to handle some really basic "incoming" JSON, but I didn't really want a robust library. – user19747167 Aug 19 '22 at 04:47

2 Answers2

4

No, you can't do it in C++. C++ is a statically typed language. Types are defined in compile time.

But you can use std::map to store key value pairs if you like. Something like this will work for you:

std::map<std::string, std::variant<int, std::string>> ss;
ss["name"] = std::string("");
ss["age"]  = 0;
std::cout << std::get<std::string>(ss["name"]) << ","
    << std::get<int>(ss["age"]) << std::endl;
1

Any way I can do something like this?

No, there is no way to do this in C++. That's not how c++ works. In particular, struct ss = {}; is not even valid syntax.

struct ss = {}; // invalid syntax in c++

When we provide a definition for struct ss say by writing struct ss{};, then we're telling the compiler(at compile time) that there aren't any members.

If you want to have members name and age then you'll have to provide them inside the class definition:

struct ss 
{
    std::string name;
    int age = 0; 
};

int main()
{
    ss obj;
    std::cout << obj.name <<std::endl;
    std::cout << obj.age << std::endl;
}
Jason
  • 36,170
  • 5
  • 26
  • 60