Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ How to declare a class as local to a file

So, I know static functions are functions that are local to the file. Thus, they can't be accessed from other files. Does this work for classes too? I've read a ton of controversy on how static class does not declare the class to contain purely static members and methods (which is obvious), but couldn't find anything that mentioned whether or not this would declare the class to be locally accessible to the file scope, as is more logical.

In case it doesn't, what about using an anonymous namespace, which I've heard also can be used to declare file local functions?

like image 839
Codesmith Avatar asked Nov 22 '16 23:11

Codesmith


People also ask

Can you define a class in a CPP file?

Class definitions can be put in header files in order to facilitate reuse in multiple files or multiple projects. Traditionally, the class definition is put in a header file of the same name as the class, and the member functions defined outside of the class are put in a . cpp file of the same name as the class.

How do I use a class in another cpp file?

In any file where you want to use your class, just include its header file. If you use your class in the main C++ file, you would include your header in the . cpp file for main. // main.

How do you declare a class?

You can declare a class by writing the name of the next to the class keyword, followed by the flower braces. Within these, you need to define the body (contents) of the class i.e. fields and methods. To make the class accessible to all (classes) you need to make it public.

How do you declare a local class in C++?

A local class is declared within a function definition. Declarations in a local class can only use type names, enumerations, static variables from the enclosing scope, as well as external variables and functions.


1 Answers

You can define a class in unnamed namespace as for example

namespace
{
    struct A {};
}

In this case the class name will have internal linkage. That is it is visible only in the compilation unit where it is defined and all compilation units that include that definition will have their own class definitions.

As for the storage class specifier static then (7.1.1 Storage class specifiers)

5 The static specifier can be applied only to names of variables and functions and to anonymous unions

like image 81
Vlad from Moscow Avatar answered Oct 19 '22 20:10

Vlad from Moscow