I know we cannot declare a static
member variable inside a local class... but the reason for it is not clear.
So please can anybody explain it?
Also, why can't we access a non-static
variable defined inside the function, within which the local class has been defined, directly in the local class member functions?
In the code given below:
int main(int argc, char *argv[])
{
static size_t staticValue = 0;
class Local
{
int d_argc; // non-static data members OK
public:
enum // enums OK
{
value = 5
};
Local(int argc) // constructors and member functions OK
: // in-class implementation required
d_argc(argc)
{
// global data: accessible
cout << "Local constructor\n";
// static function variables: accessible
staticValue += 5;
}
static void hello() // static member functions: OK
{
cout << "hello world\n";
}
};
Local::hello(); // call Local static member
Local loc(argc); // define object of a local class.
return 0;
}
Static variable staticValue
is directly accessible while on the other hand the argc
argument from main
is not....
class interface; // base class declared somewhere
// creates specific implementations
interface* factory( int arg ) // arg is a local variable
{
struct impl0: interface { /* ... */ }; // local class
struct impl1: interface { /* ... */ }; // local class
// ...
switch ( arg )
{
case 0: return new impl0;
case 1: return new impl1;
// ...
}
return 0;
}
The locally declared class instance would now exist beyond the lifespan of the function local variables.
The two questions are related. I believe the answer is not clear to you because the static
keyword in C++ has overloaded meanings.
When you define a static variable inside the function, you're really telling the compiler to initialize it only in the first call (so you can use the value across multiple calls). This is not exactly the same of the case of a file-scope or class-scope static variable.
With this in mind it might not make sense to define a static variable inside a local class, which is in turn defined inside a function.
Regarding your second question, a local class actually can access static variables defined in its enclosing function. The code below, for example, should compile in a standards-compliant compiler.
void f()
{
static int i;
class local
{
int g() { return i; }
};
local l;
/* ... */
}
int main()
{
f();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With