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 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_attribute
and static_method()
are declared as 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.
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.
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 }
Obrigado pelo seu feedback!