cody said:
statics are like global variables but reside in a class.
I think the OP asked for a static method variable.
static method variables are initialized the first time the statment
where is is defined is called and are destroyed upon program termination.
The code below shows how it all works.
#include <iostream>
struct foo
{
const char * str;
foo( const char * i_str )
: str( i_str )
{
std::cout << "making foo" << str << "\n";
}
~foo()
{
std::cout << "deleting foo" << str << "\n";
}
void useme()
{
std::cout << "using foo" << str << "\n";
}
};
struct zoo
{
void method( int v = 0 )
{
static foo static_method_variable( "First" );
static_method_variable.useme();
if ( v == 0 )
{
static foo static_method_variable( "Second" );
static_method_variable.useme();
}
else if ( v == 1 )
{
static foo static_method_variable( "Third" );
static_method_variable.useme();
}
else if ( v == 2 )
{
static foo static_method_variable( "Fourth" );
static_method_variable.useme();
}
}
};
int main()
{
std::cout << "in main \n";
zoo zoo_obj1;
zoo zoo_obj2;
zoo_obj1.method( 1 );
zoo_obj2.method( 1 );
zoo_obj1.method( 0 );
zoo_obj2.method( 0 );
std::cout << "leaving main \n";
}
---- produces ----
in main
making fooFirst
using fooFirst
making fooThird
using fooThird
using fooFirst
using fooThird
using fooFirst
making fooSecond
using fooSecond
using fooFirst
using fooSecond
leaving main
deleting fooSecond
deleting fooThird
deleting fooFirst
they are already
contructed when the app starts
.... they are initialized when the code containing the statment is first
passed.
and destroyed when the app ends so allocation