Search code examples
c++classscope

How to define class attribute after creating class


I am trying to figure out how to define a Variable which is a member of a class in C++, Outside of the normal class body. It may be inside of a Function, or outside of the class. Is this possible. What I need is that the variable should be a member of the class such that if I call Nodesecond.birthdate, it returns the birthdate. I am attempting to understand the language, there is no real-world application involved.

This was my attempt at doing it:

#include <iostream>
using namespace std;

struct Nodesecond {
public:
    int Age;
    string Name;
    //  I dont want to define Birthdate here. It should be somewhere else. 

    Nodesecond() {
        this->Age = 5;
        this->Name = "baby";
        this->birthdate = "01.01.2020";
    }
};

int main() {
    std::cout << "Hello, World!" << std::endl;
    Nodesecond mynode;
    cout << mynode.Age << endl << mynode.Name << mynode.Birthdate;
    return 0;
}


Solution

  • You can do something close to JavaScript objects.

    #include <iostream>
    #include <unordered_map>
    using namespace std;
    
    struct Nodesecond {
    public:
        int Age;
        string Name;
        unordered_map<string, string> Fields;
        string& operator[](const string& name) {return Fields[name];}
        Nodesecond() {
            this->Age = 5;
            this->Name = "baby";
            *(this)["Birthdate"] = "01.01.2020";
        }
    };
    
    int main() {
        std::cout << "Hello, World!" << std::endl;
        Nodesecond mynode;
        cout << mynode.Age << endl << mynode.Name << mynode["Birthdate"];
        return 0;
    }