Reputation: 421
I was wondering if a subclass can access variables from the main.cpp file. For example:
Main.ccp
int x = 10;
int main()
{
return 0;
}
Example Class's cpp
Subclass::Subclass ()
{
x = 5;
}
Error:
error: 'x' was not declared in this scope
I am new to coding and I was wondering if this is somehow possible, and if not, how can I do something like this?
Upvotes: 3
Views: 2362
Reputation: 7255
Add extern declaration of x in class'cpp, and then the compiler will find the x definition in other cpp file itself.
A little change to the code:
Main.cpp
#include "class.h"
int x = 10;
int main()
{
return 0;
}
Example Class's cpp
#include "class.h"
extern int x;
Subclass::Subclass ()
{
x = 5;
}
Head file class.h
class Subclass {
public:
Subclass ();
};
And for extern keyword, reference this: How do I use extern to share variables between source files?
Upvotes: 2
Reputation: 4360
C++ is not java. You have no main class here, and accessing global variables from a method in a class is not a problem. The problem is accessing a variable that is defined in another compilation unit (another source file).
The way to solve the problem is to make sure the variable is defined in the compilation unit where you use it, either just like Vaughn Cato suggests (while I'm typing this).
Upvotes: 1
Reputation: 64308
This is possible, although generally not a good idea:
Main.ccp
int x = 10;
int main()
{
return 0;
}
Example Class's cpp
extern int x;
Subclass::Subclass ()
{
x = 5;
}
Probably what you want to do instead is to pass a reference to x
to the relevant classes or functions.
At the very least, it would be a good idea to structure it differently:
x.hpp:
extern int x;
x.cpp
#include "x.hpp"
int x = 10;
class.cpp:
#include "x.hpp"
Subclass::Subclass()
{
x = 5;
}
Upvotes: 5