Home > database >  How to define class attribute after creating class
How to define class attribute after creating class

Time:11-23

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

CodePudding user response:

This is not possible, since the class has to be complete by compiletime. However, under some circumstances a std::map<Key,Value> might do the job.

CodePudding user response:

How to define class attribute after creating class

You can't. Everything that the class has, needs to be specified/declared in the member-specification of the class.


Note the emphasis on declared in the previous statement. We must declare everything first inside the class and then we can optionally define that afterwards outside the class.

CodePudding user response:

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