0

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
10
  • What is the point of having static and const applied to the same variable?
    – Logicrat
    Commented Nov 25, 2020 at 13:11
  • @Logicrat the value of a static data member can be changed unless it is declared as const. Commented Nov 25, 2020 at 13:17
  • 2
    What exactly is your question? Is there a way you want to initialize b that does not work? Commented Nov 25, 2020 at 13:21
  • 1
    You already do that in the part you commented out, so what's wrong with that approach?
    – t.niese
    Commented Nov 25, 2020 at 13:35
  • 2
    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
    Commented Nov 25, 2020 at 14:08

2 Answers 2

2

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.

6
  • 1
    While I personally agree that this is probably the cleanest way to do it, the question is how can i initialize static const int member outside class ? and that one is not outside of the class. Maybe it is what the OP is looking for, but then the question is asked incorrectly by the OP.
    – t.niese
    Commented Nov 25, 2020 at 14:12
  • @t.niese please read carefully. I want to initialaize members out of class. Can i do it?? Commented Nov 25, 2020 at 14:51
  • @user12918858 I didn't say anything else in my comment?
    – t.niese
    Commented Nov 25, 2020 at 14:57
  • @user12918858 to me it is a xyproblem.info: you're asking about how to handle a case that is already solved in modern C++: no need to discuss initialization outside the class if it can (and should) be done where it's declared (so inside, with inline).
    – Quarra
    Commented Nov 25, 2020 at 17:39
  • @Quarra and how to initialize from main? Commented Nov 25, 2020 at 17:42
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.