Bloomberg LP Interview Question
Software Engineer / Developerscan check this at :- http://www.research.att.com/~bs/bs_faq2.html
Why is the size of an empty class not zero?
To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:
class Empty { };
void f()
{
Empty a, b;
if (&a == &b) cout << "impossible: report error to compiler supplier";
Empty* p1 = new Empty;
Empty* p2 = new Empty;
if (p1 == p2) cout << "impossible: report error to compiler supplier";
}
There is an interesting rule that says that an empty base class need not be represented by a separate byte:
struct X : Empty {
int a;
// ...
};
void f(X* p)
{
void* p1 = p;
void* p2 = &p->a;
if (p1 == p2) cout << "nice: good optimizer";
}
This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".
I simply did not understand the basis of this question. Come on i have also worked in this technology for so many years and have used extensively. why would some one do that or ask such a question.
My Ans: I dont know
Q: what if the class has one empty function ? what would be its size ?
My Ans : Size would be incremented by 4 bytes on a 32 bit system than the previous size.
Q: what if the function is made virtual ? what would be its size ?
My Ans : Class Size would be the same.
Compiler will generate 1 byte of memory to mark the existence of the class.
The reason is that all classes must have a memory size of at least 1 byte so that the class doesn't occupy the same memory space with another class. This is to prevent name mangling. i.e. if I declare a class A {}; the compiler will still generate an entry in its table to something called "A". If behind that I declare another class say class B if A takes 0 bytes of memory and B's data gets written in the place where A was declared. In this case an instantiation of A would take on the properties of B.
the key point of the question is, for an empty class, compiler will add default constructor/destructor/copy constructor/assignment operator to the class. you need to take that into consideration.
- ron August 08, 2006For virtual functions, there will be a vtbl defined in the class object, thus the size will become larger. i dont know how large it will be though.