intmain(int argv, char** argc){ Player* player = new Player(28); // entity class can only be accessed by pointer( -> ) instead of instance( . ) cout << player->getValue() << endl; return0; }
Protect private member from mutability in Player class:
private: // step1: static instance should be in scope of private static Player pl_; // step2: constructor must be in scope of private Player (int value = 0) { val_ = value; }
int val_; };
// step5: initialize the static private instance in global // Decomposite it to "Player" and "Player::pl_(42)" // First "Player" means the type of pl_, second "Player" is the class name, "pl_(42)" is to initilize "pl_" by invoking constructor //Player::pl() would invoke the Player(int val = 0) constructor under the private scope to initialize pl_ to 42. Player Player::pl_(42);
Reference material: Book: Thinking in C++, Volume 1, 2nd Edition, Bruce Eckel. Lectures: University of Waterloo, CS 247 (Software Abstraction and Specificati), 2020 spring term, professor Scott Chen.
Author:Run Zeng
Slogan:Be my own hero. Never never never give up...