Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

compiler construction - c++ sizeof() of a class with functions

I have a C++ question. I wrote the following class:

class c
{
    int f(int x, int y){ return x; }
};

the sizeof() of class c returns "1". I I really don't understand why it returns 1.

Trying to understand better what is going on, I added another function:

class c
{
     int f(int x, int y){ return x; }
     int g(int x, int y){ return x; }
};

Now the following really got me confused! sizeof(c) is still 1 (!?!?!?!). So I guess that functions doesn't change the size of the class, but why??? and why does the size is 1 ? And is it compiler specific ?

Thanks! :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The class contains no data members, so it's empty. The standard demands that every class have at least size 1, so that's what you get. (Member functions aren't physically "inside" a class, they're really just free functions with a hidden argument and a namespace and access control.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...