Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why field inside a local class cannot be static?

void foo (int x)
{
  struct A { static const int d = 0; }; // error
}

Other than the reference from standard, is there any motivation behind this to disallow static field inside an inner class ?

error: field `foo(int)::A::d' in local class cannot be static

Edit: However, static member functions are allowed. I have one use case for such scenario. Suppose I want foo() to be called only for PODs then I can implement it like,

template<typename T>
void foo (T x)
{
  struct A { static const T d = 0; }; // many compilers allow double, float etc.
}

foo() should pass for PODs only (if static is allowed) and not for other data types. This is just one use case which comes to my mind.

like image 389
iammilind Avatar asked May 26 '11 10:05

iammilind


People also ask

Can local classes be static?

Local classes are non-static because they have access to instance members of the enclosing block. Consequently, they cannot contain most kinds of static declarations.

Why can't we declare a class as static?

We can't declare outer (top level) class as static because the static keyword is meant for providing memory and executing logic without creating Objects, a class does not have a value logic directly, so the static keyword is not allowed for outer class.

Why we Cannot declare static variable inside a static method?

Static variables in methods i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.

Can we declare static variable in inner class?

Since inner classes are associated with the instance, we can't have any static variables in them. The object of java inner class are part of the outer class object and to create an instance of the inner class, we first need to create an instance of outer class.


1 Answers

I guess it's because static class members have to be defined in global scope.

Edit:

Sorry for being a slacker and just throwing out stuff :) To be a little more precise. Static members of a class need to be defined in global scope, e.g.

foo.h

class A {
  static int dude;
};

foo.cpp

int A::dude = 314;

Now, since the scope inside void foo(int x) is not global, there is no scope to define the static member. Hope this was a bit clearer.

like image 103
ralphtheninja Avatar answered Sep 21 '22 14:09

ralphtheninja