This question was asked to me in an interview:
What is a static constructor?
Does it exist in C++? If yes, please explain it wit
Other way to emulate static constructor behaviour is to use instance variable with private constructor and static factory method.
Cat* Cat::give_birth() {
static Cat *myone = NULL;
if (myone == NULL) {
myone = new Cat();
}
return myone;
}
There is no such thing in C++. Constructors and destrcutors typically used to create or destruct instance of object. It's meaningless to call them without corresponding object instance. You can emulate them using a singleton pattern.
May be they mean this:
class Cat
{
private:
Cat();
public:
static Cat getCat() {return Cat(); }
}
Static constructors exist in C# and Java.
They are used to initialize static members of a class.
The runtime executes them before the class is first used.
See my answer to a similar question. C#'s static-constructor metaphor can be done in C++.
Since we do not technically have static constructors in C++, you have to decide whether it is worth it to do something tricky to force the issue (e.g. using a static instance of a nested class), or to just slightly restructure your code to call a static initializer early in your program's life.
#include <iostream> // cout, endl
class Foo {
public:
static int s_count;
// Constructor definition
Foo (int l, int w, int h)
{
cout <<"Foo ctor called." << endl;
length = l;
width = w;
height = h;
// Increase every time object is created
s_count++;
}
int vol ()
{
return length * width * height;
}
static void initCount()
{
s_count = 0;
}
static int getCount()
{
return s_count;
}
private:
double length; // Length of a box
double width; // Width of a box
double height; // Height of a box
};
// Initialize static member of class Foo
int Foo::s_count; // Initializing here is non-deterministic
int main(void) {
Foo::initCount(); // Initializing here is deterministic
// Print total number of objects before creating object.
cout << "Inital Count: " << Foo::getCount() << endl;
Foo Foo1(3, 1, 1); // Declare box1
Foo Foo2(8, 6, 2); // Declare box2
// Print total number of objects after creating object.
cout << "Final Count: " << Foo::getCount() << endl;
return 0;
}
Output:
$ static_init_test
Inital Count: 0
Foo ctor called.
Foo ctor called.
Final Count: 2
I like this approach better; as a silver lining, it takes the non- out of non-deterministic initialization.
There is one gotcha though -- this technique is insufficient if you are trying to initialize static const variables. For static const variables, you will have to make them private to the class and provide getters for outsiders to read them.
Note: I updated this code -- it compiles and runs successfully with no warnings via:
g++ static_init_test.cpp -std=c++11 -o static_init_test