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.
- Why array index starts from zero ?
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- list::empty() and list::size() in C++ STL
- queue::empty() and queue::size() in C++ STL
- stack empty() and stack size() in C++ STL
- deque::empty() and deque::size() in C++ STL
- priority_queue::empty() and priority_queue::size() in C++ STL
- vector::empty() and vector::size() in C++ STL
- Why "&" is not used for strings in scanf() function?
- Why variable name does not start with numbers in C ?
- Why only subtraction of addresses allowed and not division/addition/multiplication
- Why does sizeof(x++) not increment x in C?
- Why strcpy and strncpy are not safe to use?
- Get the stack size and set the stack size of thread attribute in C
- How to convert a class to another class type in C++?
- Difference between Base class and Derived class in C++
- How to print "GeeksforGeeks" with empty main() in C, C++ and Java?
- Print "Hello World" with empty or blank main in C++
- forward_list::front() and forward_list::empty() in C++ STL
- array::empty() in C++ STL