dekuShrub
dekuShrub

Reputation: 486

What is the scope of a class declaration in C++?

What is the scope of a class declaration? In particular: if I declare a class in a source file, is it within the global scope or the translation unit scope or other? Also... How do I declare a class only in the scope of the translation unit, like a static variable?

(for example: can I declare a class in some source file without having to worry about accidentally accessing it in my main source file?)

Upvotes: 0

Views: 1851

Answers (1)

eerorika
eerorika

Reputation: 238301

The scope of a class is the namespace where the class is declared. If it is declared in the global namespace, then the class is global.

A class must be defined in every translation unit that ODR-use the class. All TUs that refer to a class name always refer to the same class, not a TU specific class. The definition of a class must be identical across all TUs.

How do I declare a class only in the scope of the translation unit

You can use an unnamed namespace:

namespace {
    struct this_TU_only {
        int member;
    };
}

Defining following class in another TU would not be a problem:

namespace {
    struct this_TU_only {
        float member;
    };
}

This is because an unnamed namespace is distinct in each translation unit.

Upvotes: 3

Related Questions