Search code examples
c++classduplicatestoken

Does a compiler collapse classes which are identical in their structure?


I hope this isn't a duplicate of a question itself, but the search terms are so ambiguous, I can't think of anything better.

Say we have two classes:

class FloatRect
{
 float x,y,width,height;
};

and somewhere else

class FloatBox
{
 float top,left,bottom,right;
};

From a practical standpoint, they're the same, so does the compiler treat them both as some sort of typedef?

Or will it produce two separate units of code?

I'm curious because I'd like to go beyond typedefs and make a few variants of a type to improve readability.

I don't want needless duplication, though...


Solution

  • This is completely implementation specific.

    For example I can use CLang / LLVM to illustrate both point of view at once:

    • CLang is the C++ front-end, it uses two distinct types to resolve function calls etc... and treats them as completely different values
    • LLVM is the optimizer backend, it doesn't care (yet) about names, but only structural representation, and will therefore collapse them in a single type... or even entirely remove the time definition if useless.

    If the question is about: does introducing a similarly laid-out class creates overhead, then the answer is no, so write the classes that you need.

    Note: the same happens for functions, ie the optimizer can merge blocks of functions that are identical to get tighter code, this is not a reason to copy/paste though