regarding sizeof operator for class with no data variables

Discussion in 'C++' started by pratap, Aug 19, 2007.

  1. pratap

    pratap Guest

    consider this code snippet

    #include<iostream>
    using namespace std;

    class A
    {
    void func()
    {
    }
    void func1()
    {
    }
    void func2()
    {
    }
    void func3()
    {
    }
    };

    int main()
    {
    cout<<sizeof(A)<<endl;
    return 0;
    }

    why is the compiler forced to allocate 1 byte of memory for a class
    which contains no data members.suppose i define more than 1 functions
    inside this class ,why is the size of the class still 1 byte. What is
    the reason for the allocation of 1 byte by the compiler for the class
    A.

    Regards
    Pratap
     
    pratap, Aug 19, 2007
    #1
    1. Advertisements

  2. pratap

    Rolf Magnus Guest

    pratap wrote:

    > consider this code snippet
    >
    > #include<iostream>
    > using namespace std;
    >
    > class A
    > {
    > void func()
    > {
    > }
    > void func1()
    > {
    > }
    > void func2()
    > {
    > }
    > void func3()
    > {
    > }
    > };
    >
    > int main()
    > {
    > cout<<sizeof(A)<<endl;
    > return 0;
    > }
    >
    > why is the compiler forced to allocate 1 byte of memory for a class
    > which contains no data members.


    Because each object must have a distinct address, but to have an address, it
    must actually occupy storage. Think of an array of A. How could each
    element have a different address?

    > suppose i define more than 1 functions inside this class ,why is the size
    > of the class still 1 byte.


    Why not? sizeof(A) actually doesn't give you the size of the class, since
    classes don't have a size. It gives you the size of an instance of that
    class. Functions don't have a size either.

    > What is the reason for the allocation of 1 byte by the compiler for the
    > class A.


    It could be any value. The standard just requires it to be at least one
    byte.
     
    Rolf Magnus, Aug 20, 2007
    #2
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. GRenard
    Replies:
    2
    Views:
    512
    Salt_Peter
    Nov 3, 2006
  2. pratap
    Replies:
    0
    Views:
    333
    pratap
    Aug 19, 2007
  3. pratap
    Replies:
    3
    Views:
    292
    =?ISO-8859-1?Q?Erik_Wikstr=F6m?=
    Aug 20, 2007
  4. Kislay

    The sizeof operator : sizeof(++i)

    Kislay, Oct 18, 2007, in forum: C Programming
    Replies:
    10
    Views:
    788
    Peter Pichler
    Oct 19, 2007
  5. Nikolai Weibull

    sizeof(Class)/sizeof(Object)

    Nikolai Weibull, Dec 31, 2004, in forum: Ruby
    Replies:
    2
    Views:
    221
    Robert Klemme
    Dec 31, 2004
Loading...

Share This Page