0

suppose i have a simple C++ class :

class Calc
{
    private:
            int a;
    public:
            Calc(){
                    a = 0;
            }
            void seta(int a){
                    this->a = a;
            }
            int geta(){
                    return a;
            }
};

Now, suppose, in main i create a object of this class, and take two inputs from user : var_name which is name of instance variable in string format, and action which is set or get in string format. For ex : if var_name = "a" and action == "get" , then i should be able to call geta() fn. Is there any way to achieve this in C++.

pls dont provide if..then..else kind of soln. I want to write a generic code which need not be updated as more members are added in class Calc.

1
  • 1
    Nope, there's no langauage supported way of doing this. You're trying to do something at runtime that is baked in at compile time. Commented Jun 16, 2016 at 9:43

1 Answer 1

2

You cannot dynamically modify C++ types. However, it sounds like you just want a way to set and read attributes. You don't need to modify your class structure for this, there are other alternative solutions. For example you could use an std::map:

class Calc
{
    private:
            std::map<std::string, int> attributes;
    public:
            Calc(){}

            void setAttr(const std::string& name, int value){
                    attributes[name] = value;
            }
            int getAttr(const std::string& name){
                    return attributes[name];
            }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.