Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

c++ - What good are public variables then?

I'm a total newbie with tons of ?'s in my mind and a lot to experience with C++ yet! There's been something which I find really confusing and it's the use of public variables, I've seen tons of code like this:

class Foo {

private:
    int m_somePrivateVar;

public:
    void setThatPrivateVar (int const & new_val) {
        m_somePrivateVar = new_val;
    }

    int getThatPrivateVar (void) const {
        return m_somePrivateVar;
    }

};

Why would anyone hide that variable and implement accessors and mutators when there's nothing done in them more than assigning the new value just as it got received (no range checking etc.) or returning the value without just as it is? Well I've heard some reasons and some of them are convincing in some cases, but imagine implementing a huge class in such a manner for with a lot of variables which do not need any checking and stuff! Let me ask you this way, When do you use public variables? Do you use that at all?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By hiding the variable and adding methods now, the class designer allows for inserting arbitrary code into those methods in the future without breaking tons of code that use the attributes directly.

Also note that providing a lot of accessor/mutator methods is generally a sign that your class design needs another look for possible improvement. Class methods should implement actual logic, not just provide access to each member.

I use public variables only in struct form. For example, I might have a database table that represents a string->value mapping, where value is a composite data structure. I'd just write a structure and use for example std::map<std::string, MyStruct> to represent the database table. I don't need to actually do work on the data, merely be able to look it up and make use of it when required.

As noted in a couple comments, even structs can often benefit from judicial use of methods, for example a couple of common constructors to keep the members sanely initialized, a clear function to reuse the structure, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...