Dog.h
class Dog
{
public:
int *pVal;
Dog(int);
~Dog();
static int GetVal(Dog d);
};
Dog.cpp
Dog::Dog(int val)
{
pVal = new int;
*pVal = val;
}
Dog::~Dog()
{
delete pVal;
}
int Dog::GetVal(Dog d)
{
return *(d.pVal);
}
Test
Dog fido(20);
CHECK(Dog::GetVal(fido) == 20);
Dog rex(21);
CHECK(Dog::GetVal(fido) == 20);
CHECK(Dog::GetVal(rex) == 21);
The first CHECK goes fine. However, as soon as I declare Dog rex(21), my fido object's pVal gets overridden by 21. By debugging, I have noticed that on calling new int in the constructor the pVal of rex gets the same memory address as the fido object's pVal. I tried a lot, but could not find anything.
What is the correct way of initializing the pointer and assigning the value to it?
Please help. Thank you in advance.