Static Keyword. (Doubt)

I Dont Understand this code.

code:-
#include<iostream>
using namespace std;
class sample
{
static int c; //declaring static c initialised to zero
//before first object created
public:
sample()
{
c++; //increment static variable
}
int getcount()
{
return c;
}
static int d; //public static
};
int sample::c=0; //definition of c
int sample::d; //definition of d


Questions:-
1. Should static variable always be created outside the access specifier?
2. What will happen if i declare the variable inside public?
3. Where all do we have to use the static funtion?
4. Should it be only static variables for static funtions?


1. Should static variable always be created outside the access specifier?


That just means that it is private. if it had been a struct instead of a class, it would be public. That is the only difference between class and struct.

2. What will happen if i declare the variable inside public?


It's usually a bad idea to have public or protected variables.

3. Where all do we have to use the static funtion?

https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm

4. Yes.
4. It's less "should" and more "must". If you try to access a non-static member from a static member the compiler will reject the program (unless you do it via an instance of the class). Non-static members can use static members, however.
Registered users can post here. Sign in or register to post.