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.
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.
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.
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.
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).
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;
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