Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Class TestClass {
- public:
- // localVariable exists only inside doThings() - once doThings() finishes, localVariable will be destroyed.,
- inline void doThings(int localVariable = 10)
- {
- // Because classVariable is a member of TestClass, it exists as long as the instance of the class does
- classVariable = localVariable;
- }
- int classVariable = 5;
- };
- int main ()
- {
- TestClass dongs = new TestClass();
- // Prints "5", because when we create the class, classVariable defaults to 5
- printf("%d", dongs.classVariable);
- dongs.doThings(2020);
- // Prints "2020", because we gave the value 2020 to doThings, and it created localVariable with value of 2020, and then copied that value in to classVariable
- printf("%d", dongs.classVariable);
- dongs.doThings();
- // Prints 10, because the default value of localVariable is 10. We didn't give it a value, so it uses default.
- printf("%d", dongs.classVariable);
- /*
- * No where inside main can we ever say: dongs.localVariable - it doesn't exist in the class, it only exists *inside* the function doThings.
- * We can never go TestClass.classVariable or TestClass::classVariable, because TestClass is the name of the class.
- * To access any function or variable, we need to create an instance of the class (first line of main()). UNLESS, the function or variable is static - then it persists even if we don't create an instance of the class
- */
- }
Add Comment
Please, Sign In to add comment