I have the following code to test out my understanding of basic pointers in C++:
// Integer.cpp
#include \"Integer.h\"
Integer::Integer()
{
value = new int;
Think about this call:
displayInteger( "intVal1", intVal1 );
You are creating a copy of intVal1
into the intObj
parameter of displayInteger
:
void displayInteger( char* str, Integer intObj )
{
cout << str << " is " << intObj.getInteger() << endl;
}
That copy will be pointing to the same int
that intVal1
is. When displayInteger
returns, intObj
is destroyed, which will cause the int
to be destroyed, and the pointer in intVal1
to be pointing to an invalid object. At that point all bets are off (A.K.A. undefined behavior) if you try to access the value. A similar thing happens for intVal2
.
At a more general level, by removing the copy constructor, you are violating the Rule of Three, which typically leads to these kinds of problems.