-1

Does an empty C++ class that is included in the compilation but is completely unused take up memory during run time? If so, how can I tell?

Ex.

#include <iostream>

int main() {
    int a, b;

    // random operations
    a = 100;
    b = a ^ 0x2904af3e;
    a = b & 0xf92c92db;

    std::cout << a << " " << b << std::endl;

    return 0;
}

// does this take any memory?
class Empty {

};
mario_sunny
  • 1,412
  • 11
  • 29
  • 3
    No, it doesn't. –  May 12 '18 at 19:29
  • @NeilButterworth I got back 1 byte when I used sizeof(Empty). I am using the Gnu C++ compiler. – mario_sunny May 12 '18 at 19:30
  • 5
    That's the size if memory that an instance of the class would take up if you instantiated it - if you don't instantiate it, it doesn't take up any memory. –  May 12 '18 at 19:31
  • I think you can find an answer here https://stackoverflow.com/questions/2362097/why-is-the-size-of-an-empty-class-in-c-not-zero – Reda Meskali May 12 '18 at 19:32
  • @NeilButterworth OK. Thanks for the clarification. So the class itself would not have any memory overhead during run time? – mario_sunny May 12 '18 at 19:32
  • @n.m. Well, there are such things as static member variables. –  May 12 '18 at 19:33
  • For even more fun, check out this question that was asked just a few minutes ago: [In C++, why does a derived class that just contains a union with an instance of its base class take more memory than the size of the union?](https://stackoverflow.com/questions/50309913/in-c-why-does-a-derived-class-that-just-contains-a-union-with-an-instance-of) – user4581301 May 12 '18 at 19:33
  • @NeilButterworth They are objects. – n. m. could be an AI May 12 '18 at 19:33
  • @mario No, it wouldn't. –  May 12 '18 at 19:33

1 Answers1

0

A type which goes unused will be something the compiler can safely ignore. The standard of course says nothing about how much room things take, but any compiler worth using will eliminate unused types. Or functions. Or any other thing that never actually gets used.

However, unused in the above case means unusued: no code anywhere uses that name. The compiler still must note that the name exists, and if someone else tries to declare a class with that name whose definition is different, you get an ODR violation. Which compilers don't have to report.

Even if a type is never used to declare an object, the compiler may have to generate some data about it if you do use the name. For example, if you invoke typeid upon this name. The compiler will have to statically create type information about it that gets bundled into your executable.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982