Reputation: 79
Im trying to get this program to take the users input and put that into a public function and assign it to the privateVariable, then I want it to return the value of privateVariable to main() and output it to the screen, but all it displays is the value of an undefined int ( -858993460 ). What logical problem am I having here ?
#include <iostream>
#include <string>
using namespace std;
class MyClass
{
private:
int privateVariable;
public:
int userVariable;
void setVariable(int userVariable)
{
privateVariable = userVariable;
}
int getVariable()
{
return privateVariable;
}
};
int main()
{
int userVariable;
cin >> userVariable;
MyClass object1;
MyClass object2;
object1.setVariable(userVariable);
object2.getVariable();
cout << object2.getVariable();
system("PAUSE");
return 0;
}
Upvotes: 2
Views: 1646
Reputation: 258618
You are not setting the variable. You call setVariable
on object1
and getVariable
on object2
, so the member of object1
remains uninitialized.
object1.setVariable(5); // object1.privateVariable = 5
// object2.privateVariable -> still uninitialized
object2.getVariable(); // returns uninitialized variable
For this to work, depending on what you want:
class MyClass
{
private:
static int privateVariable;
//......
}
This way, privateVariable will be a class-scoped member, not instance-scoped. That means it has the same value for all instances of the class (and even if instances were not created). This also means you can make both your functions static:
class MyClass
{
private:
static int privateVariable;
public:
static void setVariable(int userVariable)
{
privateVariable = userVariable;
}
static int getVariable()
{
return privateVariable;
}
};
and you can call the methods without instances:
MyClass::setVariable(5); //MyClass.privateVariable = 5;
MyClass::getVariable(); //returns 5
object1.getVariable(); //returns also 5
Another option is, if you don't want static members, to set the member for both objects:
object1.setVariable(5); // object1.privateVariable = 5
// object2.privateVariable -> still uninitialized
object2.setVariable(5); //object2.privateVariable = 5
object2.getVariable(); // returns 5
Or, you could define a constructor and set the variable there:
class MyClass
{
private:
static int privateVariable;
//......
public:
MyClass()
{
privateVariable = 5;
}
}
With this, every object you create will have the member initialized to 5.
Upvotes: 1
Reputation: 46037
You are setting in object1
and getting from object2
. object1
and object2
are different objects. As variable in object2
is not set, you get a garbage value.
And I see no use of public userVariable
in MyClass
.
Upvotes: 6
Reputation: 2391
object2 does not have your variable initialized as you set it on object1, the code you posted would only work if privateVariable was static.
Upvotes: 0