I would like to implement a method that changes the values of the fields.
I wouldn't be so certain you should do that.
You see, the fields of a struct are, by default, publicly-accessible - which means anyone can change them, method or no method. Why bother writing such a method? Isn't it redundant?
If you had a class instead of a struct, or if you had set your field access to protected or private, then it makes sense to have a method for setting field value, e.g.:
#include <string>
#include <string_view>
struct Person {
protected:
std::string name = "Ivan";
std::string gender = "Male";
public:
void changeName(std::string_view new_name) {
name = new_name;
}
};
(string_view is new in C++17; before that, you could use const std::string&).
But even then it's not always a good idea to have that. Also, in this struct of yours, there's a default name and gender, without a good reason. Instead of both these things, you might make the struct immutable:
#include <string>
struct Person {
const std::string name;
const std::string gender;
};
which, for many applications, makes sense (e.g. if you get this from some database, rather than tracking a person's name and gender throughout their lives).
std::stringrather thanchar *.std::string_viewis more appropriate.