Static member is accessible to class object.

The below mentioned code looks strange to me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

template <long I>
struct Fibo 
{
    static const long value = Fibo<I - 1>::value + Fibo<I - 2>::value;
};

template <> struct Fibo<1> { static const long value = 1; };
template <> struct Fibo<0> { static const long value = 0; };

int main()
{
    
    std::cout << Fibo<4>::value;
    Fibo<5> obj;
    std::cout << obj.value;
    return 0;
}

Last edited on
That is because it is strange...

It is using C++’s template metalanguage to recursively compute a value (possibly very inefficiently — hopefully the compiler keeps a memoized list of precomputed values), but it is totally valid C++17.


To answer your title question, a static member element is not bound to any instance of the object; you can access it either with or without an object. So both lines 14 (no object) and line 16 (object) are valid. You could also create a temporary object:

 
  std::cout << Fibo<6>{}.value << "\n";

Hope this helps.
I was under the impression that static members can't be accessed via class objects. RESOLVED..!!
I was under the impression that static members can't be accessed via class objects.

But... that's the entire point of static members - that there is one value shared by all objects of the same class, and that they can be considered to members of the class as a whole, rather than of a single object.

I feel like you may have misunderstood something important here. Can you explain what it was you thought they were for?
Topic archived. No new replies allowed.