I’m learning about classes and objects in c++ and tried the following code to test if I understood it properly:
#include <iostream>
using namespace std;
class class1
{
public:
void write(int x)
{
dataObject.var = x;
}
};
class class2
{
public:
void read()
{
std::cout << dataObject.var;
}
};
class data
{
public:
int var;
data()
{
var = 1;
}
};
int main()
{
data dataObject;
class1 object1;
class2 object2;
object2.read(data dataObject);
object1.write(2);
object2.read(data dataObject);
return 0;
}
This was for two objects to both be used to modify and use the members of a third but I get the following errors:
In member function 'void class1::write(int)':
line 10: error: 'dataObject' was not declared in this scope
In member function 'void class2::read()':
line 14: error: 'dataObject' was not declared in this scope
In function 'int main()':
line 40 + 42: error: expected primary-expression before 'dataObject'
Any idea where I am going wrong?
Thanks in advance.
EDIT:
Thanks for all the suggestions. My code now is:
#include <iostream>
using namespace std;
class class1
{
public:
void write(data &dataObject, int x)
{
dataObject.var = x;
}
};
class class2
{
public:
void read(data dataObject)
{
std::cout << dataObject.var << endl;
}
};
class data
{
public:
int var;
data()
{
var = 1;
}
};
int main()
{
data dataObject;
class1 object1;
class2 object2;
object2.read(dataObject);
object1.write(dataObject,2);
object2.read(dataObject);
return 0;
}
And I now get the errors:
8 error: ‘data’ has not been declared
10 error: request for member ‘var’ in ‘dataObject’, which is of non-class type ‘int’
18 error: ‘data’ has not been declared
20 error: request for member ‘var’ in ‘dataObject’, which is of non-class type ‘int’
40 error: ‘dataObject’ was not declared in this scope
Where you go wrong is that at this point:
there is no
dataObject. You are trying to make your classes depend on some global object. First of all you have to decide if you really want this. And if you do, you need a way to ensure that these global objects are declared and instantiated before they get used by the classes.There are many ways to fix the error, but first you need to be clear about what you want the classes to do and how they should interact with each other.
One example of how you could fix this without global objects:
Then in the main: