
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Hello World
- C++ Omitting Namespace
- C++ Tokens
- C++ Constants/Literals
- C++ Keywords
- C++ Identifiers
- C++ Data Types
- C++ Numeric Data Types
- C++ Character Data Type
- C++ Boolean Data Type
- C++ Variable Types
- C++ Variable Scope
- C++ Multiple Variables
- C++ Basic Input/Output
- C++ Modifier Types
- C++ Storage Classes
- C++ Numbers
- C++ Enumeration
- C++ Enum Class
- C++ References
- C++ Date & Time
- C++ Operators
- C++ Arithmetic Operators
- C++ Relational Operators
- C++ Logical Operators
- C++ Bitwise Operators
- C++ Assignment Operators
- C++ sizeof Operator
- C++ Conditional Operator
- C++ Comma Operator
- C++ Member Operators
- C++ Casting Operators
- C++ Pointer Operators
- C++ Operators Precedence
- C++ Unary Operators
- C++ Control Statements
- C++ Decision Making
- C++ if Statement
- C++ if else Statement
- C++ Nested if Statements
- C++ switch Statement
- C++ Nested switch Statements
- C++ Loop Types
- C++ while Loop
- C++ for Loop
- C++ do while Loop
- C++ Foreach Loop
- C++ Nested Loops
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ Strings
- C++ Strings
- C++ Loop Through a String
- C++ String Length
- C++ String Concatenation
- C++ String Comparison
- C++ Functions
- C++ Functions
- C++ Multiple Function Parameters
- C++ Recursive Function
- C++ Return Values
- C++ Function Overloading
- C++ Function Overriding
- C++ Default Arguments
- C++ Arrays
- C++ Arrays
- C++ Multidimensional Arrays
- C++ Pointer to an Array
- C++ Passing Arrays to Functions
- C++ Return Array from Functions
- C++ Structure & Union
- C++ Structures
- C++ Unions
- C++ Pointers
- C++ Pointers
- C++ Dereferencing
- C++ Modify Pointers
- C++ Class and Objects
- C++ Object Oriented
- C++ Classes & Objects
- C++ Class Member Functions
- C++ Class Access Modifiers
- C++ Static Class Members
- C++ Static Data Members
- C++ Static Member Function
- C++ Inline Functions
- C++ this Pointer
- C++ Friend Functions
- C++ Pointer to Classes
- C++ Constructors
- C++ Constructor & Destructor
- C++ Default Constructors
- C++ Parameterized Constructors
- C++ Copy Constructor
- C++ Constructor Overloading
- C++ Constructor with Default Arguments
- C++ Delegating Constructors
- C++ Constructor Initialization List
- C++ Dynamic Initialization Using Constructors
- C++ Inheritance
- C++ Inheritance
- C++ Multiple Inheritance
- C++ Multilevel Inheritance
- C++ Object-oriented
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Virtual Function
- C++ Pure Virtual Functions & Abstract Classes
- C++ File Handling
- C++ Files and Streams
- C++ Reading From File
- C++ Advanced
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
- C++ Socket Programming
- C++ Concurrency
- C++ Advanced Concepts
- C++ Lambda Expression
- C++ unordered_multiset
Static Data Members in C++
Static Data Members in C++
In C++, a static data member is a class member or class-level variable, which is shared by all instances(objects) of that class. This is not like regular data members, which have separate copies for each object of the class, a static data member has only one copy for the entire class, which can be shared across all instances, which means that all objects of the class can access and modify the same value.
Static Data Member Declaration
This is the following syntax for declaring a static data member inside the class using a static keyword.
class ClassName { public: static dataType staticMemberName; };
Static Data Member Initialization
This is the following syntax for defining and initializing a static data member outside the class, which is done using ClassName:: scope resolution operator.
dataType ClassName::staticMemberName = initialValue;
Accessing Static Data Members
Static data members can be accessed in two ways, that is −
- Using the Class Name (Recommended)
- Using an Object (Not Recommended)
Here we will see the following differences between them and their syntax and examples.
Accessing Static Data Members Using the Class Name
This is the very common and preferred way of accessing a static data member, which is done by using the scope resolution operator ::
Syntax
Here is the following syntax for it.
ClassName::staticDataMember;
Accessing Static Data Members Using an Object
You can also access a static data member using an object, but it's generally not recommended because static members are independent of any specific object, and using an object can mislead it.
Syntax
Here is the following syntax for it.
objectName.staticDataMember;
Example
Here is the following example of a static data member in C++.
#include <iostream> #include <string> using namespace std; class Book { private: string title; // Title of the book string author; // Author of the book public: // Static data member to track total books in the library static int totalBooks; // Constructor to initialize the book's title and author Book(string bookTitle, string bookAuthor) { title = bookTitle; author = bookAuthor; totalBooks++; // Increment totalBooks every time a new book is created } // Static method to display the total number of books static void displayTotalBooks() { cout << "Total number of books in the library: " << totalBooks << endl; } // Method to display information about the book void displayBookInfo() { cout << "Book Title: " << title << ", Author: " << author << endl; } }; // Initialize the static data member outside the class int Book::totalBooks = 0; int main() { // Creating book objects (books being added to the library) Book book1("The Catcher in the Rye", "J.D. Salinger"); Book book2("To Kill a Mockingbird", "Harper Lee"); Book book3("1984", "George Orwell"); // Displaying the total number of books using the static method Book::displayTotalBooks(); // Displaying the details of each book book1.displayBookInfo(); book2.displayBookInfo(); book3.displayBookInfo(); // Adding more books to the library Book book4("Pride and Prejudice", "Jane Austen"); Book book5("The Great Gatsby", "F. Scott Fitzgerald"); // Displaying the updated total number of books Book::displayTotalBooks(); return 0; }
Output
Total number of books in the library: 3 Book Title: The Catcher in the Rye, Author: J.D. Salinger Book Title: To Kill a Mockingbird, Author: Harper Lee Book Title: 1984, Author: George Orwell Total number of books in the library: 5
Use Case of Static Data Members
Static data members in C++ are the names given to those variables that can be accessed by all instances of a class. That is, they are not tied to any object. Let's see some common use cases for it.
1. Tracking object creation
A very common usage of static data members is to track the number of instances or objects for a class.
2. Maintaining global configurations or settings
These are used to create global settings or configuration components that need to be accessed by all instances of a class in any context.
3. Cache or Shared Resource Management
Static data members are also useful for managing shared resources or caching in a system, where it's possible for multiple objects to access the same resource.
4. Implementing design patterns like Singleton
The implementation of design patterns, such as Singleton, is also advantageous, as this particular pattern often uses static data members to ensure that there exists only one instance of a class throughout the entire program. The static member holds the exclusive instance of the class.
5. Tracking global counters or actions across objects
It also helps in tracking a global count of a particular object or action, like counting the number of logins, transactions, or events.