Bruce
Bruce

Reputation: 35233

What is the purpose of static class in C++?

I recently encountered the definition of static class in C++ while going through the source code of ns2 simulator:

static class TCPHeaderClass : public PacketHeaderClass {
public:
        TCPHeaderClass() : PacketHeaderClass("PacketHeader/TCP",
                         sizeof(hdr_tcp)) {
        bind_offset(&hdr_tcp::offset_);
    }
} class_tcphdr;

I have never encountered a static class in C++ before. What are the properties and uses of the same?

Upvotes: 6

Views: 241

Answers (4)

juanchopanza
juanchopanza

Reputation: 227390

That is an unusual syntax to declare a static instance of TCPHeaderClass called class_tcphdr, equivalent to

class TCPHeaderClass : public PacketHeaderClass {
public:
    TCPHeaderClass() : PacketHeaderClass("PacketHeader/TCP", sizeof(hdr_tcp)) {
        bind_offset(&hdr_tcp::offset_);
    }
};

static TCPHeaderClass class_tcphdr;

Upvotes: 10

Caesar
Caesar

Reputation: 9841

The class is not static, it is the class_tcphdr that is static.

Upvotes: 1

Linuxios
Linuxios

Reputation: 35783

The variable class tcphdr is static, not the class. C++ has no concept of a static class, only namespaces. Look in C# and like languages for static classes.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355039

It is not the class that is static, it is the variable class_tcphdr.

Your code is equivalent to:

class TCPHeaderClass : public PacketHeaderClass { /* etc. */ };

static TCPHeaderClass class_tcphdr;

Upvotes: 5

Related Questions