is there anything like static constructors or destructors in C++
? if yes, how to implement it?
How do you mean? Constructors initialise and destructors uninitialise
objects, so they need an object to act upon. Thus, they cannot be static. Or
you are using some other meaning of words "constructor", "destructor" and
"static"!?
One thing comes to mind... You can have plain functions or static class
methods which can create objects ("factory methods"), this way:
class SomeClass
{
public:
SomeClass &operator=(SomeClass const &org) { /* implement assignment
operator if not trivial */ }
~SomeClass() { /* implement destructor if not trivial */ }
static SomeClass CreateSomeClass(/* for example */ int param1, bool
param2)
{
SomeClass retval(param1);
if (param2) { retval.DoSomeStuff(); }
return retval;
}
private:
explicit SomeClass(/* for example*/ int param) { /* implement a
constructor */ }
SomeClass(SomeClass const &org) { /* implement copy constructor if not
trivial */ }
void DoSomeStuff() { /* ... */ }
/* ... */
};
In this example, you can create SomeClass objects only calling
CreateSomeClass with two parameters supplied. The value is returned via the
private copy constructor, while it is created by invoking a private
constructor of any kind (in the above example - one-parameter constructor)
with any further processing needed to create the object of a desired kind
(in the above example - conditional call to DoSomeStuff()). Note that this
approach requires one or two copy constructor calls to create a SomeClass
object (depending on how good the compiler optimisations are), so it may not
be efficient for a particular purpose. Also note that it is usually not good
to have this kind of copy semantics for polymorphic classes (e.g. classes in
a inheritance hierarchy).
You could move CreateSomeClass outside of SomeClass by declaring it as a
friend of SomeClass, if desired.
Rade