Download presentation
Presentation is loading. Please wait.
Published byChristina Carlson Modified over 6 years ago
1
static in Classes CSCE 121 J. Michael Moore
2
Recall Attributes and methods belong to an instance of the class.
Sometimes, we want to have Attributes that are shared by all instances of the class. Methods that can be called without an instance of the class. Frequently used for constants related to a class. For example, if you are creating student objects and you want a running count of how many students there are, you can have an int accessible by any instance of a class. Maybe you need to know if a value is valid for use in a class without needing to have an instance of the class available.
3
Make things ‘static’ ‘static’ keyword
Static attributes and methods belong to the class not to an instance of a class. Add before declaration of attribute or method. This makes the data member a declaration only, not a definition. Therefore, must define and initialize data member outside of the class. Use scope resolution operator (::) to access. Can be accessed and called even if there are no instances of the class.
4
Creating & Using static members
class MyClass { static int numMade; // declaration public: MyClass() : { numMade++; } static getNumMade() { return numMade; } }; int MyClass::numMade = 0; // initialize int main() { cout << “numMade: “ << MyClass::getNumMade() << endl; MyClass m1; MyClass m2; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.