-1

I am an iphone programmer and know the way how getter and setter works.(That property and synthesize)

But I am not familiar with other languages and want to know that if I am creating a variable in language like c ++ & accessing it by creating object of its class.
then does system creates a getter and setter for that automatically?
Or I need to do some extra works?

sajwan
  • 333
  • 3
  • 14

3 Answers3

3

C++ does not offer any kind of functionality for that, unfortunately, you have to write the getters and setters manually.

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:

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

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

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

In general, here's how getters and setters work in C++:

class Person
{
  public:
     const std::string& name() const {
         return name_;
     }

     void name(const std::string& name) {
         name_ = name;
     }

  private:
    std::string name_;
};

int main()
{
    Person pers;
    pers.name("John");
    std::cout << pers.name();

    return 0;
}

A lot of people like to name those functions getName() and setName(), but I prefer to have it like this. Also remember to always make your getters const (eg.: at the end of const std::string& name() const) — this will signal to the compiler that the function won't modify the Person object.

Edit: As you can see, in C++ getters and setter are just like any other method, there's absolutely nothing special about them.

Paul Manta
  • 30,618
  • 31
  • 128
  • 208
  • Why would you need to expose the name? For printing? Then make the stream operator a friend. There is no need to expose name. You are creating a tight coupling to your class that you will need to maintain even if it is never required. – Martin York Dec 22 '11 at 09:57
  • @LokiAstari Just an example. Anyway, what use would the class be if I can't read anything about it (I have no getters)? – Paul Manta Dec 22 '11 at 09:58
  • 1
    You expose the action that can be performed on the class via methods. There is practically never a reason to expose the implementation to anything but the interface. – Martin York Dec 22 '11 at 10:01
  • @LokiAstari How is this exposing the implementation? The name could be stored as anything, all I know is that there's a getter and setter pair available that uses `std::string`. – Paul Manta Dec 22 '11 at 10:04
  • You are coupling it to std::string and must maintain this string interface (even if the internal structure changes now you will need to maintain that interface). If you had just exposed it to the stream operator for printing then you would have no coupling and never any extra work. – Martin York Dec 22 '11 at 10:06
  • @LokiAstari But what if I want to do more with the name than just print it? What if I want to store it in a vector? What if `Person` also has a job field, what should the stream operator print then? You could say that it should print both, but what if I don't want it to? What if I want to sort `Person` objects by name? – Paul Manta Dec 22 '11 at 10:09
  • I'm with Loki here - returning a reference to a string forces you to store the actual string somewhere. That limits your implementation choices. And how often do you set the name of a `Person`? It really *is* hard to find good examples with setters and getters! :-) – Bo Persson Dec 22 '11 at 10:11
  • @Bo You're right about the reference, but then again I can always modify that without affecting (good) client code. But I strongly disagree about your second statement. What am I supposed to do with the class if there's nothing I can read about it? Again, how do I, for example, sort `Person` objects by name? – Paul Manta Dec 22 '11 at 10:13
  • 1
    @Paul - You don't do something with the class, you ask the class to do it. Its member functions have access to the internals. To sort it, you can have a comparison operator, or possibly a functor that is a friend of the class (and therefore part of the interface). – Bo Persson Dec 22 '11 at 10:30
  • @PaulManta: Why would you store names in a vector (maybe you want a vector of person). This is exactly why a getter is bad. You can still sort by name by proving the appropriate helper functions. Thus only the helper functions are tightly coupled to the object not every other person that can use a method (thus not leaking your implementation). – Martin York Dec 22 '11 at 10:30
  • @Loki "Thus only the helper functions are tightly coupled to the object" The class implementation wasn't leaking before (imo), but now your helper functions show that your specific usage of the class leaked into its implementation. The vector example was not good, but the sorting example is. There's no reasonable way you can expect the class to provide a comparison function for every possible sorting criteria you might need. – Paul Manta Dec 22 '11 at 10:35
  • 2
    Wow. it was just a contrived example of how setters and getters work in the language.. – Hybrid Dec 22 '11 at 14:05
0

In c++ you'll need some extra work.

But what prevent you from testing ?

Edit:

You have to declare and code your own method exactly as for classic function

Kurt
  • 57
  • 7
0

There is no concept of getter/setters in C++ (as compared to Objective-C where it is built in)

You have to do it manually (but it's usually a bad idea).

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • getters/setters. They expose implementation details and create a tight coupling between the class and its user. It is best to let the object do the work rather than get its internal state modify it and put it back. – Martin York Dec 22 '11 at 09:43
  • There is a concept of getter/setter in C++ but not an automated one – Adel Boutros Dec 22 '11 at 09:44
  • 1
    @AdelBoutros: I have in deed. But that does not answer my question. Where in C++ do you see getters and setters. Of course you can write your own methods that do the tasks but the language (thank god) does not provide any specific facilities for them (they are just normal methods that you write). Adding getters/setters to an object just means you have designed it wrong. – Martin York Dec 22 '11 at 09:50
  • So there is no language or runtime environment feature, but there is a concept. – vikingosegundo Dec 22 '11 at 09:52
  • Read: http://stackoverflow.com/questions/760777/c-getters-setters-coding-style – Martin York Dec 22 '11 at 09:53
  • You answer is ambigious. Because when you say "concept" it does not mean built-in or automatic, that's all what I am saying. – Adel Boutros Dec 22 '11 at 09:53
  • @LokiAstari Of course you shouldn't make a getter/setter for every single variable in your class (I cover that in my answer), but that's far from saying they are a bad idea. – Paul Manta Dec 22 '11 at 09:54
  • @AdelBoutros: There is no concept of getters/setters in C++. There is the concept in getters/setters in OO (and languages like C# and Objective-C). – Martin York Dec 22 '11 at 09:59
  • @LokiAstari C++ is OO, or isn't it? And every OO language has all the concepts of OO :) Cheers man, we are not discriminating you or your opinion. So no need to feel attacked – Adel Boutros Dec 22 '11 at 10:02
  • @AdelBoutros: You miss the point. But I have updated my answer to silence these that need further help. – Martin York Dec 22 '11 at 10:05
  • @LokiAstari "Adding getters/setters to an object just means you have designed it wrong" What use would a class be if I can't 'get' any info about it? – Paul Manta Dec 22 '11 at 10:08
  • @PaulManta: You don't want to get stuff from an object. You want an object to act on things. If you want to print the object you ask the object to print itself to the passed stream (you don't ask for the name and print it to a stream). If you want the object to change city you ask the object to change location (You do not update the city field). You want the interface on your object to reflect the actions that your object does. Let the object decide how to do the stuff internally. – Martin York Dec 22 '11 at 10:11
  • @LokiAstari And how do you tell the object to change location if not through a setter? I have a collection of objects that I want to sort according to a certain field; how do I do that? – Paul Manta Dec 22 '11 at 10:16
  • The use of getters and setters is basically to hide the object itself. SO when you make a change to the object you only do it in one place (inside the getter /setters) instead of changing it in every place you used the object directly – Adel Boutros Dec 22 '11 at 10:22
  • @PaulManta: Changing location is different from setting a field. It encapsulates all the changes requrired by a move. Rather than setting each line of an address which is error prone as you may forget. You call move which not only changes your address but cancels the milk and paper and sets up cable television at your new address. Actions are verbs telling your object to perform some action. – Martin York Dec 22 '11 at 10:34
  • @PaulManta: Sorting is easy. Answer in comments on your question. – Martin York Dec 22 '11 at 10:35
  • @BoPersson So whether or not the implementation is leaked is determined by the name of the function? What you're doing is writing the same functions as I, except I call it `city` and you call it `move`. There's nothing actually stopping me from changing the internal representation of the city -- that's the whole point of having setters instead of public fields. – Paul Manta Dec 22 '11 at 10:38
  • @AdelBoutros: Thanks for the theory lesson. But getters/setters have negative side effects. They expose implementation details of your class which has nasty side effects on tightly coupling your class to a particular implementation and preventing it from changing in the future. It is better to expose your object via action methods and let the object manipulate itself. You should limit tight coupling and document it with friendship. – Martin York Dec 22 '11 at 10:38
  • @Loki "tightly coupling your class to a particular implementation" But the alternative you suggest instead couples the class to one specific usage (see sorting example). Beside, having setters (where appropriate) doesn't mean you expose the implementation: the setters are part of the interface itself. – Paul Manta Dec 22 '11 at 10:42
  • @PaulManta: The difference would be what Move() and City() do. City() would change the name of the city (not very useful as you probably want the object to do a whole bunch of stuff all of which must succeed or the move will fail). Move(MoveServiceList) now I can make my object do all the actions needed to move. Of course you could do City(MoveServiceList) but that sort of breaks the contract of what the method name implies as you are doing more that just updating the city. – Martin York Dec 22 '11 at 10:43
  • @PaulManta: No what I describe decreases coupling. getters/setters increase coupling. For example printing. I increase coupling between print( operator <<) and my object. But I decrease coupling to everything else. Even though print(operator <<) is now tightly coupled it is really just part of my interface. But nothing else becomes coupled to my object or dependant on how it works thus I have decreased coupling with the rest of the application (at the cost of coupling a single function). – Martin York Dec 22 '11 at 10:44
  • @LokiAstari In that case I would write a move function as well, because in this case it's appropriate. I'd probably still have a city getter if it's the right thing to do, because performing actions on the object but never being able to programatically determine its state makes it rather useless. – Paul Manta Dec 22 '11 at 10:47
  • @PaulManta: You keep saying you need to determine its state why. The object knows its state. Why does anybody else need to know it. You only need to know the state to perform an action. Why not let the object do the action. This is the **fundamental** concept of OO. – Martin York Dec 22 '11 at 10:49
  • @LokiAstari But yours is not a generic interface. It is coupled to one specific use, which only allows me to do very limited things with the object. If the right balance and combination of getter, setter, and action methods were present in the class, I could do a whole lot of things that don't have to be explicitly supported by the class. I wouldn't want to modify the class to give it yet another action every time something changes. I find [this article by Scott Meyers](http://drdobbs.com/cpp/184401197) to be relevant to the discussion. – Paul Manta Dec 22 '11 at 10:52
  • @Loki How do I always know what action to perform if I know nothing about the object? – Paul Manta Dec 22 '11 at 10:54
  • @PaulManta: I like the article it agrees with my point of view. – Martin York Dec 22 '11 at 10:56
  • @PaulManta: What do you want to do to the object? The object knows what can be done to itself. Just ask it to do it. That's why its called an interface. – Martin York Dec 22 '11 at 10:57
  • @LokiAstari "I like the article it agrees with my point of view." ...How? You're pretty much saying the class should be able to do by itself all I would ever want to do. (Also please respond to the first part of that comment I made.) – Paul Manta Dec 22 '11 at 11:00
  • @LokiAstari "The object knows what can be done to itself. Just ask it to do it. That's why its called an interface." The sorting example comes back up. Say I have a rather complex class and I need a few different, very specific sorting criteria: should I expect the implementer to provide of few functions like `compareNameDecresingAgeIncreasingLocationDecreasing`? I don't think that's a good idea. – Paul Manta Dec 22 '11 at 11:02