static vs. enum

closed account (zwA4jE8b)
in regards to ML380's post in thread...
http://cplusplus.com/forum/general/42144/


1
2
3
4
5
template <typename Type>
struct TObjectSizeCalculator
{
	enum {size = sizeof(Type)};
};


I was wondering why he used enum {size = (sizof(obj))};
and found that it is because only static const variables can be initialized in declaration.

So is my understanding correct that a static const variable of a class will be the same for every instance of the class that is declared. Where as the enum will allow for each instance to have its own values?
Last edited on
closed account (zb0S216C)
So is my understanding correct that a static const variable of a class will be the same for every instance of the class that is declared.

I believe so. Any static members of a structure are shared between any instances of that structure. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using std::endl;
using std::cout;
using std::cin;

struct STRUCTURE
{
    static int Member;
} Structure0, Structure1;

int STRUCTURE::Member( 3 );

int main( )
{
    cout << Structure0.Member << endl;
    cout << Structure1.Member << endl;

    STRUCTURE::Member = 5;

    cout << Structure0.Member << endl;
    cout << Structure1.Member << endl;

    cin.get( )
    return 0;
}

The output will be:
3
3
5
5
Where as the enum will allow for each instance to have its own values?

Enumerated members are constant, Therefore, modifying them is disallowed. Enumerated members can be accessed just like any other member. However, when the structure is defined, along with the enumerated members, a value is given to them. No matter how many instances of that structure you create, those values will remain the same for all instances. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using std::endl;
using std::cout;
using std::cin;

struct STRUCTURE
{
    enum Members
    {
         One, Two
    };
} Structure0, Structure1;

int main( )
{
    cout << Structure0.One << endl;
    cout << Structure1.One << endl;

    cin.get( )
    return 0;
}

The output should be zero for both couts.

Last edited on
closed account (zwA4jE8b)
cool, thank you!
closed account (zwA4jE8b)
That is very interesting, I did not know, before this, that an enum could be set to the result of an operation.
Topic archived. No new replies allowed.