3

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?

Rapture686
  • 411
  • 1
  • 4
  • 9
  • Global variables are something you should be using very rarely if ever. – Borgleader Jul 28 '13 at 03:47
  • What is the reason to do this? – awesoon Jul 28 '13 at 03:47
  • I'm using SDL and I'm making the SDL_Surface variables inside the main and I try to access them from another class and I dont know how. I need to be able to access it from both classes – Rapture686 Jul 28 '13 at 03:48
  • `main` isn't in a class. Consequently, your `Subclass` is not accessing fields of its superclass; it's accessing something else. In this case, it's a global variable declared within a different compilation unit (file). – icktoofay Jul 28 '13 at 22:16

3 Answers3

5

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;
}
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
2

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?

Community
  • 1
  • 1
lulyon
  • 6,707
  • 7
  • 32
  • 49
  • I did this an now it says undefined reference to `x' instead – Rapture686 Jul 28 '13 at 03:56
  • @user2548588 Interesting, cause it does work for me. At least you should has a class declaration in head file, and include by both cpp file, right? To be more specific, I've edited my answer. – lulyon Jul 28 '13 at 04:10
1

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).

Rasmus Kaj
  • 4,224
  • 1
  • 20
  • 23