0

I have the main function and a class, I'am trying to use an int that is in that other class in main.

main.cpp

#include <iostream>
#include "main.hpp"

using namespace std;

int main()
{
    cout << MainInt::x << endl;
    return 0;
}

main.hpp

class MainInt
{
public:
    MainInt();
    int x;
};

MainInt::MainInt()
{
    x = 1;
}

The way I am doing it currently doesn't feel right. I feel like cout << MainInt::x << endl; is just calling the variable x.

Currently I get error: invalid use of non-static data member 'x'

What I need is to call x which is a non-static variable in MainInt such that I can output the value of x on the console. How do I go about doing that?

On Demand
  • 65
  • 5

2 Answers2

1

Either x is a static variable (also known as a global variable), and in this case, this should be:

class MainInt
{
public:
    MainInt();
    static int x;
};

// in cpp:
int MainInt::x = 1;

or it's a traditional variable, as it it feels like from the constructor. In that case, you need to instantiate an object:

MainInt variable;
cout << variable.x << endl;
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • static x doesnt work I get `undefined reference to 'MainInt::x'` – On Demand Jan 09 '19 at 10:30
  • Thanks its a traditional variable the second method works – On Demand Jan 09 '19 at 10:44
  • @OnDemand The first fails because you forgot this `// in cpp: int MainInt::x = 1;` The two options are fundamentally different, they're not alternative ways of doing the same thing. – john Jan 09 '19 at 10:44
  • @Peter what's the difference with my second solution? – Matthieu Brucher Jan 09 '19 at 10:50
  • @john I know the first one declares x in the cpp which I didn't want and the second one instantiates a variant of the class I want, I normally use is for creating gtk widgets like `Gtk::Box boxname;` it didn't pass my mind that i was supposed to do the same thing here. – On Demand Jan 09 '19 at 10:53
  • @OnDemand OK fine, but that wasn't clear from your initial 'doesn't work' comment. You wouldn't be the first person not to realise that you need to define static variables – john Jan 09 '19 at 10:56
1

Using Matthieu Brucher's solution I did the following

main.cpp

#include <iostream>
#include "main.hpp"

using namespace std;

int main()
{
    MainInt x;
    cout << x.x << endl;
    return 0;
}
On Demand
  • 65
  • 5