Created
January 2, 2022 02:15
-
-
Save ak9999/accd48523ab4a2e166bd972ff1dd0186 to your computer and use it in GitHub Desktop.
Demo on using `const`.
This file contains 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> | |
static int outside_variable{0}; | |
class Demo { | |
int val; | |
public: | |
static const int inside{1}; | |
Demo(int v = 0) { | |
val = v; | |
} | |
void f1() { | |
std::cout << "f1()\n"; | |
std::cout << "static int outside_variable: " << outside_variable << '\n'; | |
} | |
void f2() const { | |
std::cout << "f2()\n"; | |
int i = 0; | |
std::cout << "Current i: " << i << '\t'; | |
++i; | |
std::cout << "Current i: " << i << '\t'; | |
// ++outside_variable; // doesn't work | |
// Does work with const_cast | |
std::cout << "Current outside_variable: " << outside_variable << '\n'; | |
++outside_variable; | |
// int &modifiable = const_cast <int &> (outside_variable); | |
// modifiable = 20; | |
std::cout << "Current outside_variable: " << outside_variable << '\n'; | |
} | |
void f3() { | |
std::cout << "f3()\n"; | |
std::cout << "static int inside: " << inside << '\n'; | |
int& writable = const_cast<int&>(inside); | |
writable = 20; | |
std::cout << "static int inside: " << inside << '\n'; | |
} | |
}; | |
int main() { | |
const Demo d; | |
Demo c; | |
c.f1(); | |
d.f2(); | |
c.f1(); | |
c.f3(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment