Software & Finance

C++ - Static Variables

Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.

If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example using new operator in C++ or malloc in C), we can see that heap size if increasing.

If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.

Example for static variabales allocation is given below:


#include <iostream>

static char msg[] = "Welcome to my static function";

void DisplayWelcomeMessage()
std::cout << msg; 
    // Accessing the msg static variable in sub function in the current file

int main()


    // Accessing the msg static variable in main function in the current file
std::cout << msg;


Can I have a static variable in a class? Of course, YES. You can have any number of static variables. The use of static variable is all the instance of the class objects can share the same object.

In fact if it is a public static variable, you do not even need any class object to access the member. You can access it by <class name>::<static variable name>.

Writing class is only a declaration and it does not allocate any memory. When you create an instance, the memory is allocated. How come static member variables of class gets allocated? You need to allocate explicitly by defining the member variable. Look at the following example on how m_pMySingletonClass is defined.

#include <iostream>


class MySingletonClass {



    int m_nValue;

    MySingletonClass() { };

    MySingletonClass(const MySingletonClass& other);

    const MySingletonClass& operator = (const MySingletonClass& other);



    static MySingletonClass* m_pMySingletonClass;

    static MySingletonClass* GetInstance()


        if(m_pMySingletonClass == NULL)

            m_pMySingletonClass = new MySingletonClass();

        return m_pMySingletonClass;



    int GetValue() const { return m_nValue; }


    void SetValue(int nVal) { m_nValue = nVal; }



// Defining the static member variable m_pMySingletonClass 
MySingletonClass* MySingletonClass::m_pMySingletonClass = NULL;


int main()

    MySingletonClass *p1 = MySingletonClass::GetInstance();

    MySingletonClass *p2 = MySingletonClass::GetInstance();


    std::cout << p2->GetValue(); // Displays 100 on the screen