Gugja Sputnik
Gugja Sputnik

Reputation: 113

class members vs. static members in Vala

I have seen https://wiki.gnome.org/Projects/Vala/Manual/Classes#Types_of_class_members and tested several times. As a result, I assume this

static members : can be accessed in a class & sub-classes of it & all instances of these
class members : can be accessed in all instances of (a class & sub-classes of it)

Is this right? And are there any other differences?

Upvotes: 2

Views: 517

Answers (1)

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

Let's check using the --ccode switch of the Vala compiler:

public class Test {
    public static int static_member;
    public class int class_member;
    public int instance_member;
}

When compiled will produce these C data structures (I only show the important parts):

struct _Test {
        gint instance_member;
};

struct _TestClass {
        gint class_member;
};

extern gint test_static_member;

The static member is not stored in any structure belonging to the class, but is a global variable. It is still scoped using the class prefix (so "test_" is prepended) to avoid name clashes with other global variables or static members of other classes.

The class member is stored in the "class structure" and the instance member is stored in the "instance structure".

The "class structure" may be extended by deriving classes, but other than that you normally only have one instance of the "class structure" for each class (which is why they are named like this).

The "instance structure" holds all the instance data everytime a new instance is created.

For the full understanding of these mechanism you have to know some C and have to read the GObject manual.

Upvotes: 4

Related Questions