Reputation: 1828
What does the line int Test::i; does in the below program. Somebody Please Explain
// Assume that integers take 4 bytes.
#include<iostream>
using namespace std;
class Test
{
static int i;
int j;
};
int Test::i;
int main()
{
cout << sizeof(Test);
return 0;
}
Upvotes: 0
Views: 81
Reputation: 17026
The line in question defines (instantiates) the static variable i in class Test and initializes it to the default value zero.
The program writes out the size of an object of type class Test, which is the size of the int "j" in bytes. The number is platform-dependent. A 32-bit Windows program will write 4. The variable "i" does not enter into it, because it is not a member of objects of class Test, but rather a "static member", which is like a global except that it is only accessible through the namespace for class Test.
Upvotes: 0
Reputation: 92864
int Test::i;
defines the static member i
of class Test
initializing it to 0
by default.
static int i;
just declares the member i
but doesn't define it. You need to put the definition separately.
Upvotes: 2
Reputation: 258588
That's the syntax for defining a static
member of a class. It initializes Test::i
to 0
.
To give it another value, you can do
int Tent::i = 42;
Upvotes: 2