Reputation: 838
Is it possible to initialize static member with its own method eg. initialize()?
Example:
class Foo
{
//some private variables
public:
static Bar example;
//some methods
}
Then call it in main.cpp like:
Foo::example.initialize(argument);
Of course it does not work. Also it has lack in encapsulation because variable is public. I woud like it to be private and initialized just once. I do not have any other option than initializing it with a method.
Upvotes: 0
Views: 72
Reputation: 5222
The default way for initializing an object should be by it's default construtor.
If it is really needed then a Singleton can be used (be aware it is an Anti-pattern: What is an anti-pattern? , also What is so bad about singletons?)
class Singleton
{
public:
static const Bar& getBarInstance()
{
static Bar bar;
return bar;
}
};
This will only be initialized once.
Upvotes: 1