A (newbie) C++ static attribute query...

Moderator
Posts: 702
Joined: 2002.04
Post: #1
To wit, is the value of a static attribute maintained when there are no objects of the class within which the static attribute is declared?

I've searched, but I can't find a definitive yes or no. A quick experiment says yes, and common sense says yes, but is tempered by my experience that common sense often isn't when dealing with C++' foibles...

Code:
#include <stdio.h>

class A
{
    private:
        static int m_i;

    public:
        A( void )
        {
            m_i ++;
            printf( "%d\n", m_i );
            return;
        };
};

int A::m_i = 0;

int main( void )
{
    A *a;
    a = new A();
    // This should print "1".
    delete a;
    // Is the value of m_i maintained whilst there are no objets of A?
    a = new A();
    // If it is, this should print "2".
    delete a;
    return 0;
}

Mark Bishop
--
Student and freelance OS X & iOS developer
Quote this message in a reply
Sage
Posts: 1,199
Joined: 2004.10
Post: #2
The answer is yes.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #3
A class' static variable can be thought of as a global variable held within the scope of the class.
Quote this message in a reply
Moderator
Posts: 702
Joined: 2002.04
Post: #4
Thanks TomorrowPlusX, akb825!

Mark Bishop
--
Student and freelance OS X & iOS developer
Quote this message in a reply
Post Reply