Created
May 15, 2011 21:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ion:dmatveev ~/devel
λ g++ buhurt.cc && ./a.out
bar: 0, baz: 0
bar: 1, baz: 1