ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Static Data Members and Functions
    Object Oriented ProgrammingTopic 8 of 24

    Static Data Members and Functions

    8 minread
    1,375words
    Intermediatelevel

    Static Data Members and Functions in C++

    In C++, static data members and static member functions are class members that have special properties, distinct from regular data members and member functions. The static keyword is used to define members that are shared by all instances of the class rather than each object having its own copy. This is useful when you want data or behavior that is common to all instances of the class.

    Let’s break down the concept of static data members and static member functions in detail.


    1. Static Data Members

    A static data member is a class variable that is shared by all instances of the class. Unlike normal data members, which have separate copies for each object, a static data member has a single copy for the entire class, regardless of how many objects are created.

    Key Characteristics of Static Data Members:

    1. Shared by All Instances: All objects of the class share a single copy of the static data member. Any change made to the static member by one object is reflected across all other objects of that class.
    2. Accessed Using the Class Name: Although static data members can be accessed by objects of the class, they are often accessed using the class name, which emphasizes that the member is shared across all instances.
    3. Initialization: Static data members must be defined outside the class (in a .cpp file or similar). They are not initialized within the class itself.
    4. Memory Allocation: Static data members are allocated memory only once, and they persist for the lifetime of the program.

    Syntax for Static Data Member:

    class ClassName {
    public:
        static type memberName;
    };
    

    Example:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        static int count;  // Static data member: shared by all Car objects
    
    public:
        Car(string b) : brand(b) {
            count++;  // Increment the static member for each object created
        }
    
        static void showCount() {
            cout << "Total cars: " << count << endl;
        }
    };
    
    // Definition of static data member outside the class
    int Car::count = 0;
    
    int main() {
        Car car1("Toyota");
        Car car2("Honda");
    
        Car::showCount();  // Calling static function using class name
    
        return 0;
    }
    

    Explanation:

    • count is a static data member. It keeps track of how many Car objects have been created.
    • The static data member is initialized outside the class with int Car::count = 0;.
    • showCount() is a static member function that accesses the static data member and prints the total number of Car objects created.
    • Since count is static, its value is shared across all instances of the Car class.

    2. Static Member Functions

    A static member function is a function that belongs to the class itself rather than to any particular object of the class. This means that static member functions can only access static data members or other static member functions. They cannot access non-static members because they do not operate on any particular instance of the class.

    Key Characteristics of Static Member Functions:

    1. Do Not Require an Object: Static member functions do not need an object to be invoked. They are invoked using the class name (though they can also be invoked via objects).
    2. Cannot Access Non-Static Members: Static member functions can only access static data members and other static member functions. They cannot directly access non-static members (because non-static members are tied to an instance of the class).
    3. Memory Allocation: Like static data members, static member functions are allocated memory only once, and they exist as long as the class exists.

    Syntax for Static Member Function:

    class ClassName {
    public:
        static returnType functionName(parameters);
    };
    

    Example:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        static int count;  // Static data member
    
    public:
        Car(string b) : brand(b) {
            count++;  // Increment the static member for each object created
        }
    
        static void showCount() {
            cout << "Total cars: " << count << endl;  // Access static member inside static function
        }
    };
    
    // Definition of static data member outside the class
    int Car::count = 0;
    
    int main() {
        Car car1("Toyota");
        Car car2("Honda");
    
        Car::showCount();  // Calling static function using class name
    
        return 0;
    }
    

    Explanation:

    • showCount() is a static member function. It is called using the class name Car::showCount().
    • Static functions like showCount() can access the static data member count because it is shared across all instances of the class.
    • The function cannot access non-static members (like brand) because static member functions do not operate on a particular instance of the class.

    Important Notes on Static Members:

    1. Static Data Members:

      • Memory allocation: Static data members are only created once when the class is first used (i.e., they persist for the lifetime of the program).
      • Initialization: Static data members need to be defined outside the class (usually in the .cpp file).
      • Shared across all instances: All objects of the class share the same static data member. Any modification made to it through one object will be reflected in all other objects of that class.
    2. Static Member Functions:

      • Cannot access non-static members: Static functions do not have a this pointer and thus cannot access non-static members directly.
      • Utility functions: Static functions are often used for utility functions or operations that don't depend on the state of any particular object but instead are related to the class as a whole.
      • Access only static members: Static functions can only access static data members or other static functions of the class.

    Example Using Both Static Data Members and Static Member Functions

    #include <iostream>
    using namespace std;
    
    class BankAccount {
    private:
        static int totalAccounts;  // Static data member to keep track of total accounts
        double balance;
    
    public:
        BankAccount(double initialBalance) {
            balance = initialBalance;
            totalAccounts++;  // Increment totalAccounts for each new object
        }
    
        // Static member function to access the static data member
        static void showTotalAccounts() {
            cout << "Total Bank Accounts: " << totalAccounts << endl;
        }
    
        void deposit(double amount) {
            balance += amount;
        }
    
        void displayBalance() const {
            cout << "Balance: " << balance << endl;
        }
    };
    
    // Definition of static data member outside the class
    int BankAccount::totalAccounts = 0;
    
    int main() {
        BankAccount account1(1000);
        BankAccount account2(5000);
    
        account1.deposit(500);
        account1.displayBalance();
    
        account2.deposit(2000);
        account2.displayBalance();
    
        // Calling static function using class name
        BankAccount::showTotalAccounts();  // Output will show 2 accounts
    
        return 0;
    }
    

    Explanation:

    • totalAccounts is a static data member. It keeps track of the number of BankAccount objects created.
    • showTotalAccounts() is a static member function that outputs the total number of BankAccount objects.
    • The static data member totalAccounts is shared across all instances of the class, and any modification (like creating a new BankAccount) affects all objects of the class.

    Summary of Static Data Members and Functions

    Aspect Static Data Members Static Member Functions
    Shared Among Objects Yes, all objects share the same copy. No, but they belong to the class, not to individual objects.
    Memory Allocation Allocated once for the entire class, not per object. Exists once per class, not per object.
    Access Can be accessed via the class or objects. Can be accessed via the class or objects.
    Access to Non-Static Members Cannot access non-static members directly. Cannot access non-static members directly.
    Initialization Must be defined outside the class. Defined within the class itself.
    Purpose Used for values shared among all objects of the class. Used for class-wide functions, not tied to individual objects.

    When to Use Static Members

    • Static Data Members: Use when you want a variable that is shared across all instances of a class (e.g., to count the number of instances).
    • Static Member Functions: Use when you need a function that operates on the class as a whole, rather than individual objects (e.g., utility functions, factory functions).
    Previous topic 7
    Const vs Non-Const Functions
    Next topic 9
    Function Overloading

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,375
      Code examples0
      DifficultyIntermediate