#### Archived

This topic is now archived and is closed to further replies.

# Forced Class Construction through static.

## Recommended Posts

Taulin    100
This was talked about a little in the Pluggable factories thread, but this question is a more general question. One important aspect of the pluggable factory is having a class with a static of itself in it so that its constructor will be forced to execute. For example:
  class Stupid { private: Stupid() { printf( "> Stupid constructor\n" ); Number++; } static const Stupid registerThis; }; 
By having that static, Number will be incremented without ever having to make an instance of Stupid. Now, for pluggable factories, there is another purpose. But here is my question. I have tried this under two compilers now ( VC, and aCC in Unix ), and when I run a program that uses this class, the Stupid''s constructor is not getting called, and Number is never increased. Am I missing something? Thanks for any ideas, this has intrigued me.

##### Share on other sites
Guest Anonymous Poster
Should the constructor really be private?

##### Share on other sites
Taulin    100
Yea, the reason for that dealt with the pluggable factories.
A pointer to ''this'' is handed to a base class, once again making the constructor being called through this ''trick'' more important.
For this question though, I should have just made it public.
Go ahead and consider it public, but I am curious about Number not being incremented through someone making an instance of Stupid, but rather that static causing it to be called.

##### Share on other sites
Taulin    100
OOps, I just figured it out. I forgot to put
in the static initializer because you can''t
initialize a static member inside the class
declaration.

  class Stupid{ . . .}const Stupid Stupid::registerThis;

Now it works dandy. Nothing like
talking through something to find the solution.