Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

How to access names by which data members are declared in c++ and output those names to console

Code:

class A
{
    private:
        int abc;
        string xyz;
}

In the above code, how can I access the names by which data members are declared (abc, xyz) and print them to console?

Upvotes: 0

Views: 45

Answers (2)

molbdnilo
molbdnilo

Reputation: 66421

If you mean accessing the names of members, as strings, without knowing those names beforehand, that's not possible - C++ doesn't support reflection.

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

The only way I can think of is using a macro:

#define PRINT_VAR(x) std::cout << #x << '\n';

C++ doesn't have the reflection capabilities of other languages.

Upvotes: 2

Related Questions