Home > Blockchain >  C class: one getter/setter for all data members?
C class: one getter/setter for all data members?

Time:08-12

I tried to practice C through some OOP, and thus has class like this:

class Obj
{
protected:
    cls1 class1;
    cls2 class2;
    ......
    clsn classn;
}

I really need to make these members protected, I suppose. then the question becomes how can other functions invoke the class data member to retrieve/modify its value. One common solution is through getter/setter functions. But it would be cumbersome to write every getter and setter for each member. So, can I achieve one uniform getter/setter member function with template?

class Obj
{
    template<typename T> int get_stats(){
        ...
        // maybe using is_same_v<T,cls1> to get what class of data member I attempt to access
        // thus confirm the data member to access? 
    };
    template<typename T> void add_stats();
}

Would that be possible, or with some other features?

CodePudding user response:

Actually, no it's not possible to do that and it would be a terrible idea to have a getter and a setter for all of your data. If you doing so, why bother put it in protected, just put it public. I'm also pretty sure that you want them private and not protected. But I don't have enough information.

When doing OOP, you don't want that the user of your class have full control of your data, you only want to expose behavior of your class through function. Kept your data private and then do not write setters. Or make them public and do not write setters.

Of course sometimes, it's good to have some setters, but I speak in a general purpose

CodePudding user response:

try to make them public or you should make a setter and getter to every variable this is for security

CodePudding user response:

you can use friend functions and classes. I suggest you read this article

  • Related