Advertisement

Forced Class Construction through static.

Started by July 19, 2000 09:55 AM
2 comments, last by Taulin 24 years, 5 months ago
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.
Should the constructor really be private?
Advertisement
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.
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.

This topic is closed to new replies.

Advertisement