In one of the interviews, I was asked given an empty class, what compiler gets for you? Can anybody please let me know what compiler will provide for any empty class?
-
Do you mean size or something else? Is an empty class exactly `class empty{};`? – Retired Ninja Sep 08 '14 at 23:09
-
Which compiler? What happened when you tried it? – Elliott Frisch Sep 08 '14 at 23:09
-
see it yourself at http://gcc.godbolt.org/ – Bryan Chen Sep 08 '14 at 23:09
-
I know the size will be '1' even though it is empty. But the interviewer asked any other things I know – kadina Sep 08 '14 at 23:10
-
@kadina What exactly was asked for? Size or something else? You're unclear as can be with the wording of your question! – πάντα ῥεῖ Sep 08 '14 at 23:18
-
possible duplicate of [What is The Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – Niall Sep 09 '14 at 07:22
1 Answers
The answer depends a lot on how the class is used and which version of C++ is involved:
The class will have non-zero size, so that pointer arithmetic works and the elements of arrays of them will be distinct.
assert(sizeof(empty_class_t) != 0)
The class will have a default constructor, if you construct any.
empty_class_t e;
The class will have a default copy constructor, if you copy any.
empty_class_t f(e);
The class will have a default copy assignment operator, if you assign any.
empty_class_t g = f;
In C++11, the class will have a default move constructor, if you use it.
empty_class_t h(std::move(g));
In C++11, the class will have a default move assignment operator, if you use it.
empty_class_t j; j = std::move(h);
I think I've got all the uses right - someone let me know of any booboos, please.
See this answer for details of when these are generated for classes in general, but basically they are only generated if the compiler can do something sensible and they are used in your code; the compiler is not required to fail where one of these default members cannot be generated but is not used.
-
-
1When you have numbered or bullet points you have to double-indent code under them. – user207421 Sep 08 '14 at 23:49