user29809
user29809

Reputation: 93

c++ class constant of its own class

Basically, I would like to declare constants of a class within the class itself:

class MyClass {
    int itsValue;
    public:
        MyClass( int anInt) : itsValue( anInt) {}
        static const MyClass CLASSCONST;
};

So I can access it like this;

MyClass myVar = MyClass::CLASSCONST;

But I can't find a way to initialize MyClass::CLASSCONST. It should be initilized inside the MyClass declaration, but at that point the constructor is not known. Any one knowing the trick or is it impossible in c++.

Upvotes: 0

Views: 105

Answers (2)

user4617155
user4617155

Reputation:

class MyClass {
    int itsValue;
    public:
        MyClass( int anInt) : itsValue( anInt) {}
        static const MyClass CLASSCONST;
};

const MyClass MyClass::CLASSCONST(42);

Upvotes: 2

a_pradhan
a_pradhan

Reputation: 3295

Here is a working example with definition outside the class. The class declaration has a const static member which is initialized outside the class as it is a static member and of type non-integral. So initialization inside the class itself is not possible.

#include <iostream>

class test
{
    int member ;
public:
    test(int m) : member{m} {}

    const static test ob ;

    friend std::ostream& operator<<(std::ostream& o, const test& t)
    {
        o << t.member ;
        return o;
    }
};

const test test::ob{2};

int main()
{
    std::cout << test::ob ;
}

Upvotes: 0

Related Questions