Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ subclass accessing main classes variables

Tags:

c++

class

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?

like image 815
Rapture686 Avatar asked Nov 19 '25 13:11

Rapture686


2 Answers

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;
}
like image 79
Vaughn Cato Avatar answered Nov 21 '25 04:11

Vaughn Cato


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?

like image 27
lulyon Avatar answered Nov 21 '25 04:11

lulyon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!