Uh, it looks like you're trying to code Java in C++.
Correct code: cpp.sh/32yf
Raw:
c++ code:
#include <iostream>
using namespace std;
class Thing {
public:
void modifyInstVar() {
test++;
}
// You had the parameter as const, but then called a modifying method on it!
void modifyOtherThing(Thing& thingRef) {
thingRef.modifyInstVar();
}
// made this public so I can see the values of test in main later -- not essential
int test;
// default constructor - sets the test field to 0 when the object is created -- important for what we want!
Thing() : test(0) {}
};
int main()
{
Thing noNew; // implicity, this is changed to Thing noNew();
// Creates a memory leak -- you dereference a pointer and assign test to this memory, but when you reassign test, this memory won't
// be automatically dealt with in C++!
Thing test = *new Thing();
Thing* testPtr = new Thing();
// Same as above ^
Thing& testRef = *new Thing();
// Proper use of references:
Thing& myTestRef = noNew;
// myTestRef is a constant pointer to noNew:
myTestRef.modifyInstVar();
// ^ we don't need to dereference a reference type - that's done automatically for us
// This means we just changed noNew's test field:
cout << noNew.test << endl;
// So we can see reference types are like aliases for the actual types to refer to
// This line then, is identical to the last:
cout << myTestRef.test << endl;
noNew.modifyInstVar(); // noNew should be 2 now
test.modifyInstVar();
testPtr->modifyInstVar();
testRef.modifyInstVar();
myTestRef.modifyInstVar(); // noNew should be 3 now
noNew.modifyOtherThing(noNew); // this shouldn't hang the compiler: its equivalent to calling noNew.modifyInstVar();, making noNew.test 4
cout << "noNew.test: " << noNew.test << endl;
noNew.modifyOtherThing(test);
cout << "test.test:" << test.test << endl;
noNew.modifyOtherThing(*testPtr);
cout << "*testPtr.test (or testPtr->test): " << testPtr->test << endl;
noNew.modifyOtherThing(testRef);
cout << "testRef.test: " << testRef.test << endl;
return 0;
}
Here is an image of the memory leak you made too:
http://gyazo.com/2e98773dad7a8eb975a62f4c8b30ac03
Its just a matter of learning how c++ does things differently.
By the way, you should try getting an IDE like Eclipse or something. If you want just a text editor, try Kate - you'll have to manually compile with g++ from the terminal though :^)
Last edited by Fear; May 31, 2015 at 09:09 PM.