-1

This is a followup to Does a class with all attributes const need to have member function declared const as well?.

So I've a class PermutationGroup whose all attribute are const. The compiler still make the distinction between const and non-const instance:

struct Foo {
  const int bar;
  void meth();
};
int main() {
   Foo foo {2};
   foo.meth();          // correct

   const Foo cfoo {1};
   cfoo.meth();         // wrong
};

As noticed by @nosid in the referred question One cannot call a non const member function a const instance:

bla.cpp: In function ‘int main()’:
bla.cpp:10:14: error: passing ‘const Foo’ as ‘this’ argument of ‘void Foo::meth()’ discards qualifiers [-fpermissive]
    cfoo.meth();

So the question is: why is it possible to declare non const instance of a class whose attribute are all const. Is there any reasonable use of that ?

Community
  • 1
  • 1
hivert
  • 10,579
  • 3
  • 31
  • 56
  • Possible duplicate of http://stackoverflow.com/questions/23449597/does-a-class-with-all-attributes-const-need-to-have-member-function-declared-con/23449626?noredirect=1#23449626. Please try to resolve problems on your original question! – πάντα ῥεῖ May 03 '14 at 21:01
  • @πάντα ῥεῖ: I didn't want to change the question on my original post. Also I don't really have a problem. I'm more wondering about good practice. – hivert May 03 '14 at 21:04
  • It would be helpful to understand, why that's important for you. Why not just declare the member functions as const? And why do you want to declare member variables as const? That's not very common. – nosid May 03 '14 at 21:04
  • @nosid: I'm modeling mathematical objects. They don't change with time. For example the integer 1 will never become 2. Another more meaningful example: it doesn't make any sense to modify the sets of all integer. – hivert May 03 '14 at 21:05
  • @hivert: `int` also mathematical objects, but they are mutable. IMO it's about object identity, not about mutability. – nosid May 03 '14 at 21:08
  • @keyser _'Use an @ symbol to ping users'_ They did ?!? ... – πάντα ῥεῖ May 03 '14 at 21:08
  • @πάντα ῥεῖ : I edited my comment after keyser remark. – hivert May 03 '14 at 21:10
  • @nosid: Thanks to your remarks ! I just realized that what I was really trying to write is a singleton pattern on a const object. I don't really need to declare my attribute const, even if it wont harm. – hivert May 03 '14 at 21:17
  • @πάνταῥεῖ No, he didn't. You can edit comments :p – keyser May 03 '14 at 22:03

1 Answers1

0

Well, a possible reasoning on why it should be allowed to declare a non-const instance in a class whose members are all const is simply the fact that you can't write the following code:

class Foo { Foo(void) const; };

Which raises:

error: constructors may not be cv-qualified

And that means, at least one member -- the constructor, and surely the destructor -- will always be non-const.

Rubens
  • 14,478
  • 11
  • 63
  • 92