-3

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?

kadina
  • 4,024
  • 3
  • 26
  • 60

1 Answers1

4

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.

Community
  • 1
  • 1
Tom
  • 5,876
  • 1
  • 31
  • 52