Monday, 9 July 2018

Static C++

static keyword can be applied to local variables, functions, class’ data members and objects in C++. static local variable retain their values between function call and initialized only once.


#include
class Test
{
public:
    Test()
    {
        std::cout << "Constructor is executed\n";
    }
    ~Test()
    {
        std::cout << "Destructor is executed\n";
    }
};
void myfunc()
{
    static Test obj;
} // Object obj is still not destroyed because it is static
 
int main()
{
    std::cout << "main() starts\n";
    myfunc();    // Destructor will not be called here
    std::cout << "main() terminates\n";
    return 0;
}
Output:
main() starts
Constructor is executed
main() terminates
Destructor is executed 
As an experiment if we remove the static keyword from the global function myfunc(), we get the output as below:
main() starts
Constructor is called
Destructor is called
main() terminates
How about global static objects?
The following program demonstrates use of global static object.
#include
class Test
{
public:
    int a;
    Test()
    {
        a = 10;
        std::cout << "Constructor is executed\n";
    }
    ~Test()
    {
        std::cout << "Destructor is executed\n";
    }
};
static Test obj;
int main()
{
    std::cout << "main() starts\n";
    std::cout << obj.a;
    std::cout << "\nmain() terminates\n";
    return 0;
}
Output:
Constructor is executed
main() starts
10
main() terminates
Destructor is executed



No comments:

Post a Comment