class ClsA { private: int var; public: ClsA() : var(0) {} ClsA(int x) : var(x) {} ... }This is what I usually did at old school. Now there is slightly little improvement on the constructor syntax. Remember how the syntax applied when a member variable is initialized by a constructor. The same syntax can be applied to trigger another constructor to perform member variable initialization. This is what the syntax called delegating constructor. Consider:
class ClsA { private: int var; public: ClsA() : ClsA(123) {} // (1) ClsA(int x) : var(x) {} // (2) ... };When I do this:
ClsA clsA;
The constructor at (1) will get invoke and further call another constructor at (2) where member variable var get initialize to 123. The constructor at (1) is a delegating constructor, (2) is a target constructor. Somehow programmer still has the flexibility to invoke constructor at (2) directly to perform its initialization. More details on this specification can be found at open-std(dot)org.
No comments:
Post a Comment