473,770 Members | 1,880 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The sizeof an empty class or structure is 1

Banfa
9,065 Recognized Expert Moderator Expert
I thought I would write a little article about this because it is regularly asked as a question in the Forums.

Firstly this is a C++ issue, it is strictly against the rules of C to create a class with no members. This makes sense because the only real use for a structure or class with no data members and virtual functions is as the base from which to derive other classes and structures or as a container for non-virtual methods.

The reason this happens boils down to properly implementing the standard, one of the things the C++ standard says is that "no object shall have the same address in memory as any other variable". There is a very good reason for this, take an array of type T then subtracting the pointer to 1 entry in the array from another should give the difference in indexes

Expand|Select|Wrap|Line Numbers
  1. T array[5];
  2.  
  3. int diff = &array[3] - &array[2];
  4.  
  5. // diff = 1
  6.  
This is actually pointer arithmetic, we have taken 2 pointers and found their difference. The compiler performs this calculation using a formula equivalent to this

diff = ((char *)&array[3] - (char *)&array[2]) / sizeof T;

This is just an example, but this type of calculation reliant on the sizeof T occurs in all sorts of pointer arithmetic.

If objects were allowed to have the same address because their type was 0 sized then this calculation would not be possible because

Expand|Select|Wrap|Line Numbers
  1. &array[3] - &array[2] = &array[3] - &array[1]
  2.                       = &array[3] - &array[1]
  3.                       = &array[3] - &array[0]
  4.                       = 0
  5.  
It is not possible to distinguish the different objects in pointer arithmetic.

Additionally there is the problem that the compiler had to divided by sizeof T, which would be a divide by zero error, although this could be coded round.

Allowing objects to have the same memory address would result in the need to implement some rather complex code to handle pointer arithmetic on them.

So objects must not have the same memory address, that is they must be individually addressable. What is the easiest way to ensure this? Make sure that all types have a non-zero size. In order to achieve this the compiler adds a dummy byte to structures and classes that have no data members and no virtual functions so that they have a size of 1 rather than a size of 0 and then they are guaranteed to have a unique memory address.
Jun 11 '07 #1
5 35795
weaknessforcats
9,208 Recognized Expert Moderator Expert
A class (or struct) can have member functions without using any data members. Unless you can create an object of this class, you can't call the methods. For this reason, a class (or struct) that has no data members is created with a sizeof 1 byte.

This also allows you to define a pointer to an object of that class. You can't define a pointer of you cannot acquire the address of an object of the pointer type. One byte is the smallest addressable memory unit. The only time in C++ when you cannot create an object of the class is when it contains (or has inherited) a pure virtual function.

Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.     public:
  4.        void AMethod() {cout << "Hello" << endl;}
  5. };
  6. int main()
  7. {
  8.     MyClass obj;
  9.     MyClass* ptr = &obj;
  10.     obj.AMethod();
  11.     ptr->AMethod();
  12.     cout << sizeof(obj) << endl;    //displays 1
  13. }
  14.  
When a class contains no data variables but does have at least one virtual function, the object is created containing the address of the virtual funciton table (VTBL) as part of the object. Because of this, the size of the object will now be 4.

Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.     public:
  4.        virtual void AMethod() {cout << "Hello" << endl;}
  5. };
  6. int main()
  7. {
  8.     MyClass obj;
  9.     MyClass* ptr = &obj;
  10.     obj.AMethod();
  11.     ptr->AMethod();
  12.     cout << sizeof(obj) << endl;    //displays 4
  13. }
  14.  
Dec 10 '07 #2
Peterwkc
55 New Member
I don't understand about the statement.

Its space overhead is one pointer in each object of a class with a virtual function plus one vtbl for each such class.

Please clear my doubt.

Thanks.
Mar 2 '08 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
I think you almost understand this.

There is one VTBL for all objects of a class with virtual functions.

Each object of the class has a pointer to that VTBL. Therefore, the overhead in each object is one pointer.
Mar 4 '08 #4
jyotis999
1 New Member
A class (or struct) can have member functions without using any data members. Unless you can create an object of this class, you can't call the methods. For this reason, a class (or struct) that has no data members is created with a sizeof 1 byte.

This also allows you to define a pointer to an object of that class. You can't define a pointer of you cannot acquire the address of an object of the pointer type. One byte is the smallest addressable memory unit. The only time in C++ when you cannot create an object of the class is when it contains (or has inherited) a pure virtual function.

Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.     public:
  4.        void AMethod() {cout << "Hello" << endl;}
  5. };
  6. int main()
  7. {
  8.     MyClass obj;
  9.     MyClass* ptr = &obj;
  10.     obj.AMethod();
  11.     ptr->AMethod();
  12.     cout << sizeof(obj) << endl;    //displays 1
  13. }
  14.  
When a class contains no data variables but does have at least one virtual function, the object is created containing the address of the virtual funciton table (VTBL) as part of the object. Because of this, the size of the object will now be 4.

Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.     public:
  4.        virtual void AMethod() {cout << "Hello" << endl;}
  5. };
  6. int main()
  7. {
  8.     MyClass obj;
  9.     MyClass* ptr = &obj;
  10.     obj.AMethod();
  11.     ptr->AMethod();
  12.     cout << sizeof(obj) << endl;    //displays 4
  13. }
  14.  
I understood that in case of virtual functions the size of the object is increasing by the VPtr (virtual pointer) which is pointing to base address of VTBLE, but please explain why it's 4 bytes exactly? why not some other value.
Oct 1 '08 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
I understood that in case of virtual functions the size of the object is increasing by the VPtr (virtual pointer) which is pointing to base address of VTBLE, but please explain why it's 4 bytes exactly? why not some other value.
It's the sizeof a memory address in a 32-bit operating system.
Oct 4 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3267
by: Sean W. Quinn | last post by:
Hey folks, I have a question regarding file handling, and the preservation of class structure. I have a class (and I will post snippets of code later in the post) with both primitive data structures (ints), and more complex data structures (strings and vectors) in it, and would like to write the entire class to a data file that could then be read back and loaded. However I'm having difficulty with this -- I found out (due to an...
2
2469
by: Xiangliang Meng | last post by:
Hi, all. What will we get from sizeof(a class without data members and virtual functions)? For example: class abnormity { public: string name() { return "abnormity"; }
4
4947
by: Sweety | last post by:
hello, why sizeof an empty class why 1 byte ? plz illustrate this ? bye
8
3091
by: ishekara | last post by:
Hi all, An object of a class A which has no member variables and no member functions, still the size of the object is 1 byte, if there is a byte member variable then also the size of the object is 1 byte. Could anyone tell me the reason behind this. Thanks ishekara
6
4888
by: free2cric | last post by:
Hi, What will the syntax sound like for checking size of an empty class? what will be the size. Thanks, Cric
4
2579
by: avranju | last post by:
Hi, We have a few exception marker classes in a project that are used only to throw exceptions. I mean stuff like this (this may not be such a hot idea for doing exception handling - a simple enum might suffice since we aren't sending any data with the exception - but that's sort of off-topic I suppose): class Whoops{}; class GeeDontKnowHowToDoThat{};
7
5999
by: dost | last post by:
can any budy tell me why the size of the empty class object is 1 thank you kapil kaushik
19
1885
by: Abubakar | last post by:
Hi, lets say I have the following class: class AAA{}; if I do: sizeof(AAA) it gives me 1. Why is the size 1 ? Regards,
2
2163
by: Harish | last post by:
This was an interview question: The size of an empty class is 1 byte. Why? Should it not be 4 bytes? Because an invisible pointer "this" is part of every class?
6
2954
by: deepakvsoni | last post by:
what is the size of an class with not data members? ex: class A { }; also sizeof ? class A{ int f(){ cout<<"Hello";
0
9617
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10037
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8931
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.