How to access static properties in an object in C++

1 Answer

0 votes
#include <iostream>

class DatabaseConnection {
private:
    // Define a private static property using C++17 'inline static' initialization.
    // This tracks active connections across all instances of the class.
    inline static int activeConnections = 0;

public:
    DatabaseConnection() {
        // Increment the shared static counter when an object is instantiated
        ++activeConnections;
    }

    ~DatabaseConnection() {
        // Decrement when an object is destroyed
        --activeConnections;
    }

    // Static member function to safely access the private static property
    static int getActiveConnections() {
        return activeConnections;
    }
};

int main() {
    // 1. Accessing static function directly via the class name (Best Practice)
    std::cout << "Initial active connections: " 
              << DatabaseConnection::getActiveConnections() << "\n";

    {
        // Create local instances within a block scope
        DatabaseConnection db1;
        DatabaseConnection db2;
        
        std::cout << "Active connections inside block: " 
                  << DatabaseConnection::getActiveConnections() << "\n";
    } // db1 and db2 are destroyed here, decrementing the counter

    std::cout << "Active connections after block scope: " 
              << DatabaseConnection::getActiveConnections() << "\n";
}


/*
run:

Initial active connections: 0
Active connections inside block: 2
Active connections after block scope: 0

*/

 



answered Oct 30 by avibootz
...