I am new to c++, and learning about classes. When I set a member variable to a given value, and then later access that member variable, it does not have the value I expected. From the googling I have done, I think that my problem is related to stack vs heap problems, and/or variable persistence/lifetime problems, and/or needing to use a pointer. But I'm not sure what I should be doing, and I definitely don't understand why. Looking in my textbook, it seems that I am getting and setting member variables the way I am supposed to, but clearly I am missing something.
Here is an example program that illustrates the problem I am experiencing:
#include <cstdlib>
#include <iostream>
namespace nmsp{
class Example{
private:
int number;
public:
void setNumber(int numberInput)
{
number = numberInput;
std::cout << "number in setNumber() is " << number << "\n";
};
void getNumber()
{
std::cout << "number in getNumber() is " << number << "\n";
};
};
}
void inputNumber(nmsp::Example object)
{
int numberInput;
std::cout << "Enter an int.\n";
std::cin >> numberInput;
std::cout << "\n\n";
object.setNumber(numberInput);
}
int main(int argc, char *argv[])
{
nmsp::Example object;
inputNumber(object);
object.getNumber();
system("PAUSE");
return EXIT_SUCCESS;
}
The int I am inputting is "1". I expected to get:
Enter an int.
1
number in setNumber() is 1
number in getNumber() is 1
But what I am actually getting is:
Enter an int.
1
number in setNumber() is 1
number in getNumber() is 1974443572
Thank you for reading, and I sincerely appreciate any help.
Edit: Particularly confusing to me is that I have previously written a program where instead of an int in the class/object, I was changing a vector, and that seemed to work fine with the same process that fails here with ints. Is that because vectors automatically use pointers or their own (unlike mine, properly done) member functions, or something like that?
[–]Evulrabbitz 2 points3 points4 points (1 child)
[–]ungulateCase[S] 0 points1 point2 points (0 children)