views:

32

answers:

1

Hello,

How do I put body of static constructor of a managed class outside class declaration? This syntax seems to be compilable, but does it really mean static constructor, or just a static (=not visible outside translation unit) function?

ref class Foo {
    static Foo();
}

static Foo::Foo() {}
+1  A: 

Yes, that is the correct syntax to create a C++/CLI static constructor. You can know its not creating a static function since that is not a valid function declaration syntax. Functions must have the return type specified. Also, the compiler would complain that Foo() is not a member of class Foo if it weren't linking it to the constructor you declared in the class definition.

You can test the fairly easily:

using namespace System;

ref class Foo {
    static Foo();
    Foo();
}

static Foo::Foo() { Console.WriteLine("Static Constructor"); }
Foo::Foo() { Console.WriteLine("Constructor"); }

int main(array<System::String ^> ^args)
{
    Foo ^f = gcnew Foo();
    Console.WriteLine("Main");
}

This would output:

Static Constructor
Constructor
Main

heavyd
Yes, thank you. I was getting an error because of that syntax, then I noticed it was because of something unrelated to static contructor.
liori