Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Static Class Definition

📅 2012-Jan-10 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, static, visual ⬩ 📚 Archive

In C++, the static specifier is only meaningful when applied on functions and variables. But surprisingly, C++ allows static to be used on a class definition:

static class Car
{
    int _speed;
};

This specifier is useless on the class definition since it does not mean anything! This compiles successfully with with Visual C++, only generating a C4091 warning:

warning C4091: 'static ' : ignored on left of 'Car' when no variable is declared

This hints at the reason why C++ allows static on a class definition. It is to support the definition of a class and the creation of a static object of that class in a single statement:

static class Car { int _speed } fooCar;

The above is equivalent to:

class Car
{
    int _speed;
};

static Car fooCar;

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧