34. Device Counter

#include <iostream>
using namespace std;

class Device {
private:
    int id;
    static int count; // static variable shared by all objects

public:
    Device(int id_) : id(id_) {
        count++; // increment when object is created
    }

    static int getCount() {
        return count;
    }
};


// static member is also required to declare out of class 
int Device::count = 0;


int main() {
    Device d1(1);
    Device d2(2);
    Device d3(3);

    cout << "Total devices created: " << Device::getCount();
    return 0;
}

Solution Details

  • If count were a normal variable, each object would have its own copy → it would reset.
     
  • By making it static, count belongs to the class, not the individual object.
     
  • All objects share this one variable, so it correctly tracks the total number created.

     

👉 In simple words:
 A normal variable is like each device keeping its own personal notebook.
 A static variable is like one shared whiteboard on the wall — every device adds to the same count.

 

Significance for Embedded Developers

  • Static variables are useful to track shared resources: how many timers, UART channels, or GPIO pins are initialized.
     
  • This ensures a global view of resource usage, no matter which object created them.

     
Loading...

Input

Expected Output

Total devices created: 3