Reputation: 149
My Projects contains multiple classes each has its own separate .h and .cpp file .
I want to declare a variable use so that I can access/modify its value from any of the classes .
Upvotes: 0
Views: 93
Reputation: 4647
You can use a public static variable in one of your classes or you can be naughty and declare a global variable outside of all your classes in one module and then use the extern keyword to reference it in other modules.
C++ is a hybrid OOP language: you don't have to use classes all the time. If you do that, be ready to get flamed by self-righteous programmers and StackOverflow lurkers.
Upvotes: 0
Reputation: 477010
You can add another translation unit to define a variable at namespace scope and make it accessible by providing a declaration:
var.h:
extern int a;
var.cpp:
#include "var.h"
int a = 15;
Now every translation unit in your program can #include "var.h"
and use a
.
It may be sensible to a) give the variable a meaningful, unambiguous name, and b) place it in a named namespace.
Upvotes: 3