-1

I am relatively new to C++ OO:

How is this getter:

class A {
  B b;
public:
  B const &getB() const {
    return b;
  }
};

different from this one?

class A {
  B b;
public:
  const B &getB() const {
    return b;
  }
};

and this one?

class A {
  B b;
public:
  const B &getB() {
    return b;
  }
};

and which one is correct?

Edit This question has an answer here: Look for "consistent const" in http://isocpp.org/wiki/faq/const-correctness#overview-const

Cœur
  • 34,719
  • 24
  • 185
  • 251
lmiguelmh
  • 2,767
  • 34
  • 49
  • 1
    1 and 2 mean the same thing, and both are correct. 3 is not technically incorrect, however since `getB()` isn't modifying the `A` instance, it makes sense for the function to be `const`, which allows it to be called on `const A` object instances (or references, etc.) – Chad Apr 13 '15 at 15:25
  • thanks for your comments but I think this question had an answer – lmiguelmh Apr 13 '15 at 15:32

1 Answers1

2

The keyword const applies on what stands before him (on his left) or, if nothing is before it, it applies on what stands after it (on his right). Your 3 cases are all correct in their uses.

You can refer to this excellent article to learn more about const-correctness : http://www.cprogramming.com/tutorial/const_correctness.html

chesh
  • 682
  • 7
  • 21