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.

Advertisements