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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- stack empty() and stack size() in C++ STL
- deque::empty() and deque::size() in C++ STL
- queue::empty() and queue::size() in C++ STL
- list::empty() and list::size() in C++ STL
- vector::empty() and vector::size() in C++ STL
- priority_queue::empty() and priority_queue::size() in C++ STL
- Difference between Base class and Derived class in C++
- set::empty() in C++ STL
- map::empty() in C++ STL
- How to convert a class to another class type in C++?
- array::empty() in C++ STL
- unordered_map empty in C++ STL
- match_results empty() in C++ STL
- unordered_multiset empty() function in C++STL
- unordered_set empty() function in C++ STL
- unordered_multimap empty() function in C++ STL
- multimap empty() function in C++ STL
- list empty() function in C++ STL
- multiset empty() function in C++ STL
- Print "Hello World" with empty or blank main in C++