Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static keyword inside a class and outside it

Tags:

c++

static

The static keyword is related to internal linkage generally, but the static keyword used inside a class has external linkage right? The variables m, n below are accessible outside the class file.

class c {
    int i;
    int j;
    static int m;
    static int n;

    public:
    void zap();
    static void clear();
};
like image 905
vkaul11 Avatar asked Aug 27 '12 23:08

vkaul11


2 Answers

Right.

The keyword static is heavily overloaded with too many different meanings:

  • On a variable or function at namespace scope it gives the name internal linkage.
  • On a class member it makes it a static member, which doesn't affect linkage.
  • On a variable at function scope it gives the variable "static storage duration" as opposed to "automatic" or "dynamic" storage duration (i.e. the variable's lifetime extends to the end of the program, like global variables.)
like image 62
Jonathan Wakely Avatar answered Sep 19 '22 15:09

Jonathan Wakely


As I stated in my comment, static members are those associated only with the class rather than individual objects.

static members belong to the class; for variables, they're accessible without an object and shared amongst instances e.g.

struct Foo {
  static void *bar;
  static void *fu();
}

so Foo::bar and Foo::fu are legal.

They are introduced in §9.4 of the C++03 standard;

  1. A data or function member of a class may be declared static in a class definition, in which case it is a static member of the class.

  2. A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated

    class process {
    public:
        static void reschedule();
    };
    process& g();
    
    void f()
    {
        process::reschedule(); // OK: no object necessary
        g().reschedule(); // g() is called
    }
    

    A static member may be referred to directly in the scope of its class or in the scope of a class derived (clause 10) from its class; in this case, the static member is referred to as if a qualified-id expression was used, with the nested-name-specifier of the qualified-id naming the class scope from which the static member is referenced.

    int g();
    struct X {
        static int g();
    };
    struct Y : X {
        static int i;
    };
    int Y::i = g(); // equivalent to Y::g();
    

    ...

like image 33
obataku Avatar answered Sep 18 '22 15:09

obataku