On Demand
On Demand

Reputation: 65

How can I use a value from another class in c++?

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?

Upvotes: 0

Views: 617

Answers (2)

On Demand
On Demand

Reputation: 65

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;
}

Upvotes: 1

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

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;

Upvotes: 1

Related Questions