Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI, static constructor outside class declaration

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() {}
like image 997
liori Avatar asked Jul 06 '10 16:07

liori


People also ask

How do you declare a constructor outside the class?

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.

Can constructor be created outside of class?

The constructor can be defined outside the class but it has to be declared inside the class.

Does C++ have static constructor?

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.

What is static constructor in c# net with 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.


1 Answers

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

like image 194
heavyd Avatar answered Oct 18 '22 15:10

heavyd