Little Jacod
Little Jacod

Reputation: 97

C++ const static initiation based on input

Hello guys i have static problem with my class:

class Monster
{
private:
     static const bool hard; 
     //more staff here
};

I know that i can initiate it like const bool Monster::hard

But I want to know if i can initiate based on users input
Something like If(wantToBeHard) hard = true;
This means it must be in a method or something right? There is any way to do this?

Upvotes: 1

Views: 1166

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

You can create a normal function (not a non-static member function) which asks for input from the user and returns a bool value:

bool AskUser()
{
    ....
}

Then simply use the return value of that function to initialize your static member.

const bool Monster::hard = AskUser();

Just to clear things up, here is a complete, compileable example:

#include <iostream>
#include <string>

bool AskUser();

class Monster
{
public:
    static bool IsHard() { return hard; }
private:
    static const bool hard;
};

int main()
{
    if (Monster::IsHard())
        std::cout << "it is hard\n";
    else
        std::cout << "it is not hard\n";
}

bool AskUser()
{
    std::cout << "hard? ";
    std::string input;
    std::getline(std::cin, input);
    return input.size() && input[0] == 'y';            
}

const bool Monster::hard = AskUser();

If you want more control over when this initialization happens, you will have to drop your requirement for const. It shouldn't really be a problem though, as long as the member is private, you can still have complete control over whether it is changed. e.g.

class Monster
{
public:
    static void SetHard()
    {
        static bool hard_is_set = false;
        if (hard_is_set)
            return;
        hard_is_set = true;
        hard = AskUser();
    }
private:
    static bool hard;
};

bool Monster::hard;

One possible problem here is that it is possible to call the SetHard function outside of main (e.g. in the initialization of another static object), if that happens, it may access the static member before it is actually created, resulting in undefined behavior. (static objects are tricky things and should be treated with care). So don't do that.

Upvotes: 5

Related Questions