user5887651
user5887651

Reputation:

C++: Get size of class instance

After writing a header and testing it (a lot), i wanted to know what the efficiency of this header was. What the header basically does is storing a map as efficiently as possible. Map.SetValue() stores a coordinate and Map.GetValue gets a coordinate. The coordinates get stored in a 2-dimensional vector, where four values get stored in one char (four possibilities per value).

I tried to get the size of the class by using this code:

int main()
{
    MapStorage Map;

    int Coords[2];
    int Value;
    int Size;
    float Efficiency;

    for (int i = 0; i < 100; i += 1){
        for (int x = 0 + 10*i; x < 10 + 10*i; x += 1){
            for (int y = 0; y < 10; y += 1){
                Coords[0] = x;
                Coords[1] = y;
                Value = rand()%4;
                Map.SetValue(Coords, Value);
            }
        }

        Size = sizeof(Map);
        Efficiency = Size/float(i+1);

        std::cout << "Size at " << i+1 << " Square meters: " << Size << ", Effficiency: " << Efficiency << std::endl;
    }

    return 0;
}

(MapStorage Map makes the class instance, as MapStorage is the name of the class)

But what happens is that this always prints that the size is 20 bytes, while at i = 99 the size should be at least 2,5kb (100 square meters, 100 values per square meter, 100*100 = 10 000, 4 values per byte, 10 000/4 = 2 500 bytes).

The question is: what am i doing wrong? do i not understand how sizeof works, or does it work differently with classes? I did some searching for other people with the same problem, but i couldn't find a solution that applies to my problem.

kind regards, Harm

notes:
I store the map as a 2D vector of type unsigned char. it's not declared as static.

Upvotes: 0

Views: 941

Answers (1)

Ajay
Ajay

Reputation: 18411

Do note that sizeof is a compile time, not runtime. The compile-time evaluated expression will be replaced by compiler with the outcome of sizeof. That's the reason, you could do this:

char bytes [ sizeof(int) ];

Which will be replaced as (if size of int on your compiler/platform is 4):

char bytes [ 4 ];

Upvotes: 2

Related Questions