Click here to Skip to main content
15,120,268 members
Please Sign up or sign in to vote.
1.67/5 (7 votes)
See more:
#include< iostream >
using namespace std;
class foo
{
private:
    static int count;
public:
    foo()
    {
        count++;
    }
    int getcount()
    {
        return count;
    }
};

int foo::count = 0;

int main()
{
    foo f1, f2, f3;
    cout << "count is " << f1.getcount() << endl;
    cout << "count is " << f2.getcount() << endl;
    cout << "count is " << f3.getcount() << endl;

    return 0;
}
Posted
Updated 2-Oct-13 10:57am
v3
Comments
Tom Wauters 2-Oct-13 15:23pm
   
I'am not sure because c++ is not my thing but is it possible that the problem might be that your class is non static and the var's are?
   
This is just the false statement. Of course they are allowed. Why not?!
I answered to the question... :-)
—SA
Maximilien 2-Oct-13 15:54pm
   
This works as expected on Visual Studio 2008; what compiler are you using ?
   
Of course. I never heard of C++ version which would not allow that. OP is just trying to mystify people... :-)
I answered to the question... :-)
—SA
Maximilien 2-Oct-13 15:58pm
   
What output did you expect ?
1
2
3

or

3
3
3

the count is incremented in the constructor so, after the line
foo f1, f2, f3;
the constructor will be called 3 times, thus count == 3.
pasztorpisti 2-Oct-13 16:25pm
   
The C++ standard forces you to define the static class members this way but if the language allowed then it would be perfectly possible to solve the definition inside the class declaration, the complexity of the solution (technically) wouldn't be more than that of the inline functions/methods declared in the header files... Why doesn't C++ allow you to do this??? I don't know but considering that C/C++ have the heritage of strictly separating declarations/definitions into header and .c/.cpp files I'm not surprised about this.

This is just the false statement. Of course they are allowed. Why not?!
I never heard of C++ version which would not allow such members, it would be against everything. :-)

[EDIT]

Please read: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr038.htm[^].

—SA
   
v2
Comments
pasztorpisti 2-Oct-13 16:20pm
   
I guess OP meant *definition* and not declaration (and definition inside the class declaration to be precise...). It is sometimes a problem that you have to define it in a class and you are not allowed to do so in the header. To circumvent this one can use a template with which it is possible to put the definition of the static member into the header file.
   
Okay, this is a good point, but just the code sample by OP compiles and works... :-)
—SA
kumar_11 2-Oct-13 16:21pm
   
Any example to understand..?
   
This one:
class foo
{
private:
static int count;
public:
foo()
{
count++;
}
int getcount()
{
return count;
}
};

:-)
—SA
kumar_11 3-Oct-13 18:33pm
   
why static const data definition is allowed inside the class..?
   
Why not?! It looks like you just asked why it is not allowed. In case of static fields, it's a way to encapsulate statically-placed per/class data. Isn't that good?
Do you really understand what statics do?
Please see the link in the updated answer, after [EDIT].
—SA
As SA said the definition of static members is allowed. I was able to compile your code and it runs without any errors from the compiler. You should have described to us exactly what error your are seeing, that greatly helps us to provide the answer that you need. BTW, I am using Visual Studio 2010, but is should work the same way in other compilers.

This is what your code is doing. The static variable foo is initialized to 0. After you declare f1, f2 & f3 their constructors are called, in the constructors count is incremented. Since all three (f1, f2 & f3) are all incrementing the same variable, count winds up being equal to 3. Then when you call getcount for each one and send the result to the console you will see 3 for each one.

If you want to have the output be different for each call to getcount you need to do the increment of count somewhere other than the constructor. Or don't construct f1, f2 and f3 before doing the output. For example if you do the following you will get 1, 2, 3 for the output.
C++
foo f1;
cout << "count is " << f1.getcount() << endl;
foo f2;
cout << "count is " << f2.getcount() << endl;
foo f3;
cout << "count is " << f3.getcount() << endl;


So that the console doesn't disappear after it runs you should add the following lines in your main method, just before the return statement:
C++
std::cout << "Press ENTER to continue... " << flush;
std::cin.ignore( std::numeric_limits <std::streamsize xmlns:std="#unknown"> ::max(), '\n' );
</std::streamsize>

The console closing may not be an issue with all IDEs, but it does happen with Visual Studio.

[Edit- add more explanation of initialization]
From your comment you seem to be bothered by the initialization of the static class member, count. It is important to understand that a static class member cannot be initialized inside of the class. While this may seem odd, it is because a static class member really exists outside of any instance of the class. You are required to initialize a static class member or it will not be conspired to be in scope inside the class. The syntax is odd, but it does work as designed. Read this article[^] for some additional explanation.

[Edit- answer why static const data definition is allowed inside the class]
The variable, count, in your code is a member of the class and is therefore declared inside the class. When you make it a static class variable you are saying that every instance of the class will share that variable. So if f1 increments count the value will be one, then if f2 increments it the value will be two, if f3 looks at count next it will see a value of two.
Because count is a static class variable is exists outside of any instance of the class, in fact count exists before any instance of the class has been created. Because of this separation count must be initialized outside of the class so that count will have its initial value when the first instance of the foo class is created.
   
v4
Comments
kumar_11 2-Oct-13 18:20pm
   
comment like:-
// int foo::count=0;
now try it.
BillW33 3-Oct-13 9:10am
   
Oh, I see, you are confused about how a a static class member is initialized. I will update my answer to better explain this part.
kumar_11 3-Oct-13 18:32pm
   
One more thing, why static const data definition is allowed inside the class..?
BillW33 4-Oct-13 9:08am
   
I will update my answer again with more information. If any of these solutions help you then you should vote them up. If any of these solutions answer your question you should mark it as the solution so that your question gets off the unanswered question list.
AlwaysLearningNewStuff 6-Oct-13 10:57am
   
My 5!
Excellent!
BillW33 6-Oct-13 11:53am
   
Thanks, I'm always learning new stuff too ;):)
C++ allows the initialization of static members inside the class declaration only in case of static const integral values.
C++
class CStaticTest
{
public:
    void Test()
    {
        printf("%s(%d)\n", __FUNCTION__, g_Member);
    }
private:
    static const int64 g_Member = 1;
};

Allowing the definition of static const integral values inside class declarations is also a new feature, not too long ago you had to resort to the unnamed enum trick to define an integer constant inside a class declaration:
C++
class CStaticTest0
{
public:
    enum { MY_INTEGER_CONSTANT = 5 };
};

Sometimes you have to define the value of some constants in header files (in case of some frameworks that need macro magic and/or template magic). In this case you can define the value of a constant in the header file by using templates. static members of templates can be defined in header files (but the definition isn't inside the template class declaration):
C++
template <typename T>
class TMyTemplate
{
public:
    void Test()
    {
        printf("%s(%s)\n", __FUNCTION__, g_Str.c_str());
    }
private:
    static const std::string g_Str;
};

template <typename T>
const std::string TMyTemplate<T>::g_Str = "MyVal";

Some header-only libraries make use of this latter feature. (/off I never understood why is it so good to write a library as header only... for other reason than increasing compile time of large projects... /on)
   
Comments
kumar_11 3-Oct-13 18:31pm
   
why static const data definition is allowed inside the class..?
pasztorpisti 4-Oct-13 4:09am
   
I don't know and probably most of us don't know this so you should ask those who define the C++ language. As I said both allowing and disallowing this kind of definition is possible technically, these are the choices of the designers of the languages.
I think your question is badly worded. It appears you wish to know the number of the class instance. You could achieve that by doing this:

C++
class foo
{
private:
    static int count;
    const int mycount;
public:
    foo() : mycount(++count)
    {
     }
    const int getcount() const
    {
        return mycount;
    }
};
 
int foo::count = 0;
 

int main()
{
    foo f1, f2, f3;
    cout << "count is " << f1.getcount() << endl;
    cout << "count is " << f2.getcount() << endl;
    cout << "count is " << f3.getcount() << endl;
 
    return 0;
}


When instances are deleted what happens to count? That's up to you.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900