Constructors in a Static Class

  • Thread starter Thread starter Jordan S.
  • Start date Start date
J

Jordan S.

Just learning OOP here... Does it make sense to have a constructor in a
static class? Say I have a class with a constructor and then mark that class
as static; will it (the default constructor) get called when the application
starts? or are any/all constructors ignored in static classes?

Thanks.
 
Jordan said:
Just learning OOP here... Does it make sense to have a constructor in a
static class? Say I have a class with a constructor and then mark that class
as static; will it (the default constructor) get called when the application
starts? or are any/all constructors ignored in static classes?

It will not compile, unless the constructor is also marked static.
And yes, it may make sense, when you need lazy initialization.
 
static constructors are automatically executed (generally) when the static
class is first used by the runtime, which could be a while into your app.
But yes, they are definitely useful. For generic static classes the ctor is
executed once per template permutation.

Marc
 
Jordan S. said:
Just learning OOP here... Does it make sense to have a constructor in a
static class? Say I have a class with a constructor and then mark that class
as static; will it (the default constructor) get called when the application
starts? or are any/all constructors ignored in static classes?

Static constructor make sense if you have static variables that you need to
initialize. Static constructors are invoked the first time the class is
accessed.
Be sure to mark the constructor as static.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top