0

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.

Ava
  • 598
  • 5
  • 13
  • 3
    Define "doesn't work". What outcome did you expect, and what did you observe instead? On the face of it, I don't see a reason why it would be a problem. If you want to make `example` private, define a static method on `Foo` that would turn around and call `example.initialize()` – Igor Tandetnik Apr 25 '18 at 14:14
  • I get "undefined reference to `Foo::example'" in main.cpp. – Ava Apr 25 '18 at 14:17
  • 2
    That's a separate problem. You have only declared `example` - you also need to define it. In some .cpp (not .h) file, write `Bar Foo::example;` – Igor Tandetnik Apr 25 '18 at 14:17
  • Oh, that's why it didn't work. Also static method tip was very helpful. Thank you. – Ava Apr 25 '18 at 14:27
  • 1
    imho encapsulation and public are orthogonal, but I know I have some crude views concerning encapsulation ;) – 463035818_is_not_a_number Apr 25 '18 at 14:43

1 Answers1

1

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.

Robert Andrzejuk
  • 4,637
  • 2
  • 20
  • 30