{"id":4869,"date":"2025-02-12T09:00:00","date_gmt":"2025-02-12T04:00:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=4869"},"modified":"2026-03-18T12:05:19","modified_gmt":"2026-03-18T07:05:19","slug":"understanding-static-data-members-and-functions-in-c","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/02\/12\/understanding-static-data-members-and-functions-in-c\/","title":{"rendered":"Static Data Members and Functions in C++"},"content":{"rendered":"\n<p>In daily life, some things are <strong>shared by everyone<\/strong> rather than belonging to just one person. For example, in a classroom the <strong>notice board<\/strong> is the same for all students. If one student puts a notice, every student can see it. Similarly, in a society, the <strong>water tank<\/strong> is shared by all houses. In C++, such shared values or functions are handled using the <code>static<\/code> keyword.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"https:\/\/afzalbadshah.com\/index.php\/2025\/02\/12\/understanding-static-data-members-and-functions-in-c\/\" width=\"640\" height=\"360\" src=\"https:\/\/www.youtube.com\/embed\/0AhTiN8zuZE?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>A static member in C++ belongs to the class itself rather than to individual objects, and its value is shared among all objects of that class.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Why Do We Need Static?<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Shared Data:<\/strong> Some values are common for all objects. For example, the total number of students in a class is the same information for all students.<\/li>\n\n\n\n<li><strong>Memory Efficiency:<\/strong> Instead of each object having its own copy, only one shared copy is created.<\/li>\n\n\n\n<li><strong>Persistence:<\/strong> A static variable keeps its value throughout the program execution, instead of being created and destroyed repeatedly.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Static Variables Inside Functions<\/h2>\n\n\n\n<p>Normally, when a variable is declared inside a function, it is created every time the function is called and destroyed when the function ends. But if it is declared as <code>static<\/code>, it is created only once and remembers its value between function calls.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nvoid demo() {\n    static int x;  \/\/ created only once\n    x++;\n    cout &lt;&lt; \"x = \" &lt;&lt; x &lt;&lt; endl;\n}\n\nint main() {\n    demo();\n    demo();\n    demo();\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 1\nx = 2\nx = 3\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Static Data Members in Classes<\/h2>\n\n\n\n<p>When a variable is declared as <code>static<\/code> inside a class, it is shared by <strong>all objects<\/strong> of that class. Only one copy exists in memory.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Program Example: Counter<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass counter {\npublic:\n    static int count;   \/\/ Declaration of static variable\n\n    counter() {\n        count++;  \/\/ Every new object increases the same shared count\n    }\n\n    static void show() {  \/\/ static function\n        cout &lt;&lt; \"The value of counter is: \" &lt;&lt; count &lt;&lt; endl;\n    }\n};\n\n\/\/ Definition of static variable outside the class\nint counter::count = 0;\n\nint main() {\n    counter C1;\n    C1.show();\n\n    counter C2;\n    C2.show();\n\n    counter C3;\n    counter::show();   \/\/ Can also be called using class name\n\n    cout &lt;&lt; \"Try programiz.pro\" &lt;&lt; endl;\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>static int count;<\/code> \u2192 declared inside the class.<\/li>\n\n\n\n<li><code>int counter::count = 0;<\/code> \u2192 defined outside the class.<\/li>\n\n\n\n<li>Every time a new object (<code>C1<\/code>, <code>C2<\/code>, <code>C3<\/code>) is created, the constructor increments <code>count<\/code>.<\/li>\n\n\n\n<li>The function <code>show()<\/code> is declared static, so it can be called without creating an object (e.g., <code>counter::show();<\/code>).<\/li>\n\n\n\n<li>All objects share the same <code>count<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Daily Life Example<\/h2>\n\n\n\n<p>Think of <strong>class attendance<\/strong>:<\/p>\n\n\n\n<p>Each student can be thought of as an object, while the attendance register in the classroom is a single shared record. No matter how many students there are, they all refer to and update the same register when marked present. In the same way, the static variable <code>count<\/code> is like that register\u2014every object (student) updates the same shared value.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Static Member Functions<\/h2>\n\n\n\n<p>A static function inside a class can be called without creating an object. It only works with static data members, since those are also shared.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class MyClass {\npublic:\n    static int value;\n    static void display() {\n        cout &lt;&lt; value &lt;&lt; endl;\n    }\n};\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Comparison: Normal vs Static Members<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Aspect<\/th><th>Normal Member<\/th><th>Static Member<\/th><\/tr><\/thead><tbody><tr><td>Storage<\/td><td>Each object has a copy<\/td><td>Shared by all objects<\/td><\/tr><tr><td>Lifetime<\/td><td>Created\/destroyed with obj<\/td><td>Exists till program ends<\/td><\/tr><tr><td>Access<\/td><td>Through objects only<\/td><td>Through objects or class<\/td><\/tr><tr><td>Memory Efficiency<\/td><td>Less efficient (duplicates)<\/td><td>More efficient (single copy)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Exercises<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Write a program to count how many objects of a class are created using a static variable.<\/li>\n\n\n\n<li>Create a static function in a class that displays the total number of books in a library.<\/li>\n\n\n\n<li>Demonstrate a static variable inside a function that keeps its value across multiple calls.<\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-embed is-type-rich is-provider-canva wp-block-embed-canva\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Static Data Members and Functions (Java)\" src=\"https:\/\/www.canva.com\/design\/DAGWbNm_eg0\/eDpLCWwnzvjmXYUs2FoVag\/view?embed&amp;meta\" height=\"360\" width=\"640\" style=\"border: none; border-radius: 8px; width: 640px; height: 360px;\" allowfullscreen=\"allowfullscreen\" allow=\"fullscreen\"><\/iframe>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>In daily life, some things are shared by everyone rather than belonging to just one person. For example, in a classroom the notice board is the same for all students. If one student puts a notice, every student can see it. Similarly, in a society, the water tank is shared by all houses. In C++, such shared values or functions are handled using the static keyword. A static member in C++ belongs to the class itself rather than to individual&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/02\/12\/understanding-static-data-members-and-functions-in-c\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":5090,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[351,637],"tags":[],"class_list":["post-4869","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-courses","category-oop-with-c"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/IMG-20241205-WA0027.webp?fit=1280%2C720&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-1gx","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4869","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=4869"}],"version-history":[{"count":11,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4869\/revisions"}],"predecessor-version":[{"id":42866,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4869\/revisions\/42866"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/5090"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=4869"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=4869"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=4869"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}