Conteúdo do Curso
C++ OOP
C++ OOP
Static Members of The Class
In object-oriented programming, the static
keyword holds a special significance, altering the behavior of attributes and methods. There are sometimes a scenarios where we need certain data to be shared among all objects of a class rather than being replicated for each instance. This is where static data members come into play.
The syntax of the static members
Creating a static member of a class is straightforward. You simply need to prepend the declaration with the static
keyword.
Example
class Example { public: static int static_attibute; static void static_method() { std::cout << "Static method!" << std::endl; } };
In the above example, static_attibute and static_method() are declared as a static data members of the class Example. Unlike regular data members, static data members are associated with the class itself rather than individual objects. This means that all instances of Example share the same static members.
Note
To access a static data member, we use the scope resolution operator (
::
). But before this we have to initialize.
Initialization is crucial for static data members, and it must be done outside the class unless the member also uses the const
keyword.
FirstExample
SecondExample
class Example { public: static int static_attribute; static void static_method() { std::cout << "Static method!" << std::endl; } }; int Example::static_attribute = 0;
Benefits of using static members
The use of static data members and static member functions offers several benefits:
-
Resource Sharing: Static data members facilitate the sharing of data among all instances of a class, reducing memory consumption and promoting efficient resource utilization.
-
Utility Functions: Static member functions can be used to implement utility functions or perform operations that are not dependent on object state.
-
Class-wide Operations: Static member functions provide a means to perform class-wide operations or manipulate class-level data without the need for object instantiation.
main
#include <iostream> class Example { public: static int static_attribute; static void static_method() { std::cout << "Static method!" << std::endl; } }; // Initialization of the static member variable int Example::static_attribute = 0; int main() { Example obj1, obj2; obj1.static_attribute = 100; // Modifying static_attribute through obj1 std::cout << obj1.static_attribute << std::endl; std::cout << obj2.static_attribute << std::endl; Example::static_attribute = 25; // Modifying static_attribute through class Example::static_method(); // Calling the static method through class }
Note
Try to experiment with a Example class and its static members
Obrigado pelo seu feedback!