Using a Class static
Member
We can access a static
member directly through the scope operator:
double r;r = Account::rate(); // access a static member using the scope operator
Even though static
members are not part of the objects of its class, we can use an object, reference, or pointer of the class type to access a static
member:
Account ac1;Account *ac2 = &ac1;// equivalent ways to call the static member rate functionr = ac1.rate(); // through an Account object or referencer = ac2->rate(); // through a pointer to an Account object
Member functions can use static
members directly, without the scope operator:
class Account {public: void calculate() { amount += amount * interestRate; }private: static double interestRate; // ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.