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?
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;
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With