Why can my c++ object not affect another c++ object?
c++
Solution
You are passing the `intHolder` by value. This means the function acts on a local copy, so there is no effect on the caller side. You need to pass a reference:
void addToOtherInt(intHolder& other) { other.addToInt(i); }
^
Note that usually when you have types that hold other types that support arithmetic operations, you provide overloaded operators so you can do things like
intHolder a = 5;
intHolder b = 10;
intHolder c = a + b;
c += 42;
a = 42 - b;
and so on. See this extensive discussion on operator overloading for more information.
Also, for "printing", it is customary to overload `ostream& operator<<`, which then allows you to stream to all kinds of streams, including but not limited to `std::cout`. For example:
struct Foo
{
int i;
};
std::ostream& operator<<(std::ostream& o, const Foo& f)
{
return o << f.i;
}
allows you to say
Foo f;
std::cout << f;
std::cerr << f;
std::ofstream tmp("foo.txt");
tmp << f;
Problem
I have a simple c++ class, intHolder, that only holds an int. It can also add to that int, which works, or add itself to another int contained in a different intHolder, which does not work. This is nothing like what I've encountered in Java. What's going on? ``` class intHolder{ private: int i; public: intHolder(int myInt){i = myInt;} void addToInt(int inc){ i = i + inc;} void printInt(){cout << i << endl;} void addToOtherInt(intHolder other){other.addToInt(i);} }; ``` Main Method ``` int main () { intHolder ih1(1); ih1.printInt();//Should be 1, is 1 ih1.addToInt(3); ih1.printInt();//Should be 4, is 4 intHolder ih2(2); ih2.printInt();//Should be 2, is 2 ih1.addToOtherInt(ih2); ih1.printInt();//Should be 4, is 4 ih2.printInt();//Should be 6, is 2 }; ```