Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • Actually const can be used in optimisation... It's undefined behaviour to modify a value defined const even after a const_cast IIRC. I'd expect it to be consistent for const member functions, but I'd need to check that with the standard. This would mean that the compiler can safely do optimisations there. Commented Jan 20, 2011 at 23:27
  • 1
    @Warren: it doesn't matter if the optimization is actually done, it's just allowed. @Kos: it's a little-known subtlety that if the original object was not declared const (int x vs. const int x), then it is safe to modify it by const_cast -ing away const on a pointer/reference to it. Otherwise, const_cast would always invoke undefined behavior, and be useless :) In this case, the compiler has no information about the const-ness of the original object, so it can't tell. Commented Jan 21, 2011 at 1:59
  • @Kos I don't think const_cast is the only issue here. The const method is allowed to read and even modify a global variable. Conversely, someone from anpther thread could also modify the const object between the calls. Commented Jul 24, 2013 at 14:47
  • 2
    The "= 0" isn't valid here and should be removed. I'd do it myself, but I'm not sure that's in conformance with SO protocol. Commented Jan 24, 2014 at 3:15
  • 1
    Both examples are invalid: the first one (int GetNumber() const = 0;) should declare the GetNumber() method virtual. The second (constexpr int GetNumber() const = 0;) isn't valid because the pure specifier (= 0) implies the method to be virtual, but constexpr's must not be virtual (ref: en.cppreference.com/w/cpp/language/constexpr) Commented Mar 4, 2016 at 10:22