Lidbey
Lidbey

Reputation: 371

Is there a way in C++ to make scoped global variables?

Let's say I have a program which uses n big modules:

A) Network/Communication

B) I/O files

C) I/O database

D) GUI

E) ...

Of course, a list of modules could be bigger.

Let's say I want to have some global variable, but with a scope limited to a single module.

As an example, let's say that I/O database module will consist of 10 classes, each representing each table in a database, but it needs some global const state like Name of table A, Columns of table A etc. (as it is a relational database, in table D I may need to use table A). It is also obvious, that I do not need to access these table names through Network/Communication module. Is there a way to make a variable "globally" accessible only for some part of classes?

Just for clarification - I know that "Global for some part" is a contradiction, but my idea is that I want to keep the accessibility(no need of pointer passing to each object), while limiting the place from where it can be called (for example, limit from global to module scope)

Upvotes: 1

Views: 422

Answers (1)

Pepijn Kramer
Pepijn Kramer

Reputation: 13110

You don't need globals for that, I strongly advise you to learn about dependency injection. Basically you have one "factory" module. And each module has an interface on you can inject an interface that has getters to access the centralized data. (e.g. members of a n instance of a class). This also allows you to test the independent modules using mocks and stubs (e.g. a test class that returns other values). –

Upvotes: 2

Related Questions