Predict the output of following program?
Size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses. See the following example.
For the same reason (different objects should have different addresses), “new” always returns pointers to distinct objects. See the following example.
Now guess the output of following program (This is tricky)
Output (with GCC compiler. See this):
Note that the output is not greater than 4. There is an interesting rule that says that an empty base class need not be represented by a separate byte. So compilers are free to make optimization in case of empty base classes. As an excercise, try the following program on your compiler.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- list::empty() and list::size() in C++ STL
- queue::empty() and queue::size() in C++ STL
- stack empty() and stack size() in C++ STL
- priority_queue::empty() and priority_queue::size() in C++ STL
- deque::empty() and deque::size() in C++ STL
- vector::empty() and vector::size() in C++ STL
- Difference between Base class and Derived class in C++
- set::empty() in C++ STL
- map::empty() in C++ STL
- array::empty() in C++ STL
- match_results empty() in C++ STL
- unordered_map empty in C++ STL
- How to convert a class to another class type in C++?
- unordered_multiset empty() function in C++STL
- unordered_multimap empty() function in C++ STL
- list empty() function in C++ STL
- multiset empty() function in C++ STL
- unordered_set empty() function in C++ STL
- multimap empty() function in C++ STL
- How to print "GeeksforGeeks" with empty main() in C, C++ and Java?