home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!sdl!sharma
- From: sharma@euler.Warren.MENTORG.COM (Sharma Kunapalli)
- Subject: Re: A question about the sizeof operator
- Message-ID: <1992Jul31.174522.692@Warren.MENTORG.COM>
- Keywords: sizeof operator
- Sender: sharma@Warren.MENTORG.COM (Sharma Kunapalli)
- Organization: Mentor Graphics Corp. - IC Group
- Date: Fri, 31 Jul 1992 17:45:22 GMT
- Lines: 81
-
- In article Message-ID: <drenze.712541103@icaen.uiowa.edu>
- drenze@icaen.uiowa.edu (Douglass J. Renze) writes:
-
- >I was playing around with the sizeof operator today, and I found out some-
- >thing curious.
- >
- >The following program:
- >
- >#include <iostream.h>
- >
- >class s1 {
- > struct name {
- > char last[10], first[10], mi;
- > };
- > s1* next;
- >};
- >
- >class s2 {
- > struct name {
- > char last[10], first[10], mi;
- > };
- >};
- >
- >int main(void) {
- > cout << "sizeof s1 = " << sizeof(s1) << '\n';
- > cout << "sizeof s2 = " << sizeof(s2) << '\n';
- > return 1;
- >}
- >
- >produces the following output:
- >
- >sizeof s1 = 4
- >sizeof s2 = 1
- >
- >Yet this next program...
- >
- >#include <iostream.h>
- >
- >class s1 {
- > char last[10], first[10], mi;
- > s1* next;
- >};
- >
- >class s2 {
- > char last[10], first[10], mi;
- >};
- >
- >int main(void) {
- > cout << "sizeof s1 = " << sizeof(s1) << '\n';
- > cout << "sizeof s2 = " << sizeof(s2) << '\n';
- > return 1;
- >}
- >
- >produces this next output...
- >
- >sizeof s1 = 26
- >sizeof s2 = 22
- >
- >Naturally I didn't expect the "sizeofs" to be *identical* between the two
- >programs (after all, one contains a struct within the class, and the other
- >doesn't), however, I did expect them to be more nearly equal than that. Can
- >anybody explain this difference to me? My curiosity is piqued. Is it that
- >the struct name isn't included within the class's memory allocation, or what?
- >
- >Peace,
- >
- >Doug
-
- In your first example,
- the nested class 'name' is in the scope of class s2
- but does not add to the size of s2.
-
- For example every s2 object does not carry a name
- object. That is why sizeof s1 is 4.
-
- Sharma
- --
- The opinions expressed here are solely mine. My company has nothing
- to do with these.
-
- Email: sharma@euler.warren.mentorg.com
-