Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>C++ does not offer any kind of functionality for that, unfortunately, you have to write the getters and setters manually.</p> <p>Since the language offers no kind of support for this kind of thing, there are a few rules of thumb you need follow to produce better quality code:</p> <ul> <li><p>All member variables should be non-public. If they need to be accessed, write a getter and/or setter. This allows you to easily modify how that variable is accessed later on, without too much trouble.</p></li> <li><p>Only members that are part of the interface (i.e.: which need to be visible) should have getters/setters. Don't start writing a getter/setter pair for every member in your class and call it encapsulation, 'cause it's not.</p></li> <li><p>If you need a setter or a getter for a variable, it doesn't automatically mean you need the other as well. In principle, only add something if you need it: it's easy to add new things, but it's hard to remove them once you already have code that uses that feature. </p></li> </ul> <p>In general, here's how getters and setters work in C++:</p> <pre><code>class Person { public: const std::string&amp; name() const { return name_; } void name(const std::string&amp; name) { name_ = name; } private: std::string name_; }; int main() { Person pers; pers.name("John"); std::cout &lt;&lt; pers.name(); return 0; } </code></pre> <p>A lot of people like to name those functions <code>getName()</code> and <code>setName()</code>, but I prefer to have it like this. Also remember to always make your getters <code>const</code> (eg.: at the end of <code>const std::string&amp; name() const</code>) &mdash; this will signal to the compiler that the function won't modify the <code>Person</code> object.</p> <p><strong>Edit:</strong> As you can see, in C++ getters and setter are just like any other method, there's absolutely nothing special about them.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload