Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading