0
votes

how can i initialize static const int member outside class ?

class C
{

public:
    C();

private:
    static const int a;
    static const std::string b;

};

// const int C::a = 4;               //  i know it 
// const std::string  C::b = "ba";  //  this one too
2
What is the point of having static and const applied to the same variable?Logicrat
@Logicrat the value of a static data member can be changed unless it is declared as const.Dmitri Chubarov
What exactly is your question? Is there a way you want to initialize b that does not work?Dmitri Chubarov
You already do that in the part you commented out, so what's wrong with that approach?t.niese
how can i initialize static const int member outside class ? besides this option is there another? You already show how to initialize them outside of the class, why do you look for another option? What do you expect from another option that you can't do with the one you show in your question? What do you not like about the one you already know?t.niese

2 Answers

2
votes

I'd go with C++17 and use inline static object:

class C
{

public:
    C() = default;
private:
    inline static const int a = 42;
    inline static const std::string b{"foo"};

};

Easiest, cleaniest, most readable.

0
votes

This is how to initialize static class members outside of the class:

C.cpp

#include <string>

class C {
public:
    C();

private:
    static const int a;
    static const std::string b;
};

C::C() = default;

const int C::a = 4;
const std::string C::b = "ba";

There is no other option to initialize a static class member outside of the class, other than all the various C++ ways to do initialization as variations on this same theme.