Skip to content

Instantly share code, notes, and snippets.

@dmatveev
Created May 15, 2011 21:13
Show Gist options
  • Save dmatveev/973545 to your computer and use it in GitHub Desktop.
Save dmatveev/973545 to your computer and use it in GitHub Desktop.
Modifying object's state from a 'const' method without of const_cast<>(this) hacks
#include <iostream>
class Foo {
int bar;
int &baz;
public:
Foo() : bar(0), baz(bar) {
}
void doIt() const {
baz++; // <<-- modifying object's state from a 'const' method!!111oneone
}
void printIt() const {
std::cout << "bar: " << bar << ", baz: " << baz << std::endl;
}
};
int main(int argc, char *argv[]) {
Foo foo;
foo.printIt();
foo.doIt();
foo.printIt();
return 0;
}
@dmatveev
Copy link
Author

ion:dmatveev ~/devel
λ g++ buhurt.cc && ./a.out
bar: 0, baz: 0
bar: 1, baz: 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment