Search code examples
c++classoverhead

Class Inside a Class in C++: Is that heavy?


Suppose I do something like:

class A
{
public:
    class B
    {
    public:
         void SomeFunction1() const;
         using atype = A;
    };

    using btype = B;
    void SomeFunction2() const;

private:
    B b;
};

Then I create an instance of class A and copy it:

A a;
A acopy = a;

Does that make the class A heavy, what I mean is, what happens in the background? I would hope that C++ doesn't really literally "consider" the definition of class B everytime I declare an instance of class A, I thin what happens in the background is that class B will be treated as a new definition under a namespace named A, so A::B is defined. My question is does defining a class inside a class (B inside A) create any overhead when declaring or copying the class A, or it's treated exactly as if B is defined outside?

Thank you everyone :)


Solution

  • Both possibilities (B as nested class and B as external class) will yield exactly the same performance.

    In fact, the compiler will generate the same assembly code in both cases.

    B as external class:

    https://godbolt.org/z/7voYGd6Mf

    B as nested class:

    https://godbolt.org/z/731dPdrqo

    B is a member of A. Hence it resides in A's memory layout and B's constructor will be called every time you constructor/copy A. The introduced overhead depends on B implementation, but it will be identical in both cases (B nested and external class),