Jump to content

what is the output and why?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
alok541

alok541

    Newbie

  • Members
  • Pip
  • 1 posts
class xyz
{

};
void main()
{
cout<<sizeof(xyz);
getch();
}


output=1 but why?
:love:

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
When you instantiate an object, it requires an address. The only way that it can be given an address is if there is SOME amount of memory it requires when it is instantiated, therefore, all class objects have to have a size in bytes of at least 1.

Imagine this situation:
xyz *o = new xyz();
If xyz is size 0, what exactly is new supposed to ask the OS for? If a request is made for 0 bytes, it is ignored, and what's worse there's no address to assign to the pointer *o, which will inevitably lead to undefined behavior when the user tries to use an object that couldn't possibly exist. Thus, your object must have at least ONE byte to assign an address in memory to, so pointers to it don't become wild or NULL for no good reason.
Wow I changed my sig!