What good are public variables then?

后端 未结 14 2229
悲哀的现实
悲哀的现实 2020-12-09 15:16

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 vari

14条回答
  •  失恋的感觉
    2020-12-09 15:31

    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 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.

提交回复
热议问题