home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / cplus / 11871 < prev    next >
Encoding:
Text File  |  1992-07-31  |  2.2 KB  |  93 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!sdl!sharma
  3. From: sharma@euler.Warren.MENTORG.COM (Sharma Kunapalli)
  4. Subject: Re: A question about the sizeof operator
  5. Message-ID: <1992Jul31.174522.692@Warren.MENTORG.COM>
  6. Keywords: sizeof operator
  7. Sender: sharma@Warren.MENTORG.COM (Sharma Kunapalli)
  8. Organization: Mentor Graphics Corp. - IC Group
  9. Date: Fri, 31 Jul 1992 17:45:22 GMT
  10. Lines: 81
  11.  
  12. In article Message-ID: <drenze.712541103@icaen.uiowa.edu>
  13. drenze@icaen.uiowa.edu (Douglass J. Renze) writes:
  14.  
  15. >I was playing around with the sizeof operator today, and I found out some-
  16. >thing curious.
  17. >
  18. >The following program:
  19. >
  20. >#include <iostream.h>
  21. >class s1 {
  22. >        struct name {
  23. >                char last[10], first[10], mi;
  24. >        };
  25. >        s1* next;
  26. >};
  27. >class s2 {
  28. >        struct name {
  29. >                char last[10], first[10], mi;
  30. >        };
  31. >};
  32. >int main(void) {
  33. >        cout << "sizeof s1 = " << sizeof(s1) << '\n';
  34. >        cout << "sizeof s2 = " << sizeof(s2) << '\n';
  35. >        return 1;
  36. >}
  37. >
  38. >produces the following output:
  39. >
  40. >sizeof s1 = 4
  41. >sizeof s2 = 1
  42. >
  43. >Yet this next program...
  44. >
  45. >#include <iostream.h>
  46. >class s1 {
  47. >        char last[10], first[10], mi;
  48. >        s1* next;
  49. >};
  50. >class s2 {
  51. >        char last[10], first[10], mi;
  52. >};
  53. >int main(void) {
  54. >        cout << "sizeof s1 = " << sizeof(s1) << '\n';
  55. >        cout << "sizeof s2 = " << sizeof(s2) << '\n';
  56. >        return 1;
  57. >}
  58. >
  59. >produces this next output...
  60. >
  61. >sizeof s1 = 26
  62. >sizeof s2 = 22
  63. >
  64. >Naturally I didn't expect the "sizeofs" to be *identical* between the two
  65. >programs (after all, one contains a struct within the class, and the other
  66. >doesn't), however, I did expect them to be more nearly equal than that.  Can
  67. >anybody explain this difference to me?  My curiosity is piqued.  Is it that
  68. >the struct name isn't included within the class's memory allocation, or what?
  69. >
  70. >Peace,
  71. >
  72. >Doug
  73.  
  74. In your first example,
  75. the nested class 'name' is in the scope of class s2 
  76. but does not add to the size of s2.
  77.  
  78. For example every s2 object does not carry a name 
  79. object. That is why sizeof s1 is 4. 
  80.  
  81. Sharma
  82. -- 
  83. The opinions expressed here are solely mine. My company has nothing
  84. to do with these.
  85.  
  86. Email: sharma@euler.warren.mentorg.com
  87.