Flavio
Flavio

Reputation: 93

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

Upvotes: 0

Views: 918

Answers (3)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38549

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

Upvotes: 2

user12002570
user12002570

Reputation: 1

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.

Upvotes: 3

Jak
Jak

Reputation: 177

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.

Upvotes: 3

Related Questions