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() {}
You can not declare a constructor outside of a class but you can define it outside of a class. Basically the standard has this to say about member function s in section 9.3. 2 : A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.
The constructor can be defined outside the class but it has to be declared inside the class.
C++ doesn't have static constructors, as Java or C# does, so you usually have to initialize the static data members one by one (independently). This is a limitation because you may want to initialize several static data members in the same loop or algorithm, for example.
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced. C# Copy. class SimpleClass { // Static variable that must be initialized at run time.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With