Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a static constructor?

Tags:

c++

This question was asked to me in an interview:

What is a static constructor?

Does it exist in C++? If yes, please explain it with an example.

like image 266
Vijay Avatar asked Apr 27 '11 12:04

Vijay


People also ask

What is a static constructor in Java?

A static constructor is the piece of code used to initialize static data, which means that a particular task needs to be executed only once throughout the program. It is usually called automatically before any static members referenced or a first instance is generated.

What is static constructor in C++?

A static constructor is used to initialize static data of a class. C++ doesn't have static constructor. But a static constructor can be emulated by using a friend class or nested class as below.

What are static and private constructors?

Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.

Do we have static constructor in C#?

Static constructor is used to initialize static data members as soon as the class is referenced first time. This article explains how to use a static constructor in C#. C# supports two types of constructors, a class constructor (static constructor) and an instance constructor (non-static constructor).


1 Answers

C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class.

class has_static_constructor {     friend class constructor;      struct constructor {         constructor() { /* do some constructing here … */ }     };      static constructor cons; };  // C++ needs to define static members externally. has_static_constructor::constructor has_static_constructor::cons; 
like image 98
Konrad Rudolph Avatar answered Oct 05 '22 11:10

Konrad Rudolph