I have this code:
#include<iostream>
class Test {
private:
int iNum;
int *ptr;
public:
Test(int iFirst, int iSecond);
void setNum(int iValue);
int getNum();
int getFirstNum();
int getSecondNum();
};
Test::Test(int iFirst, int iSecond) {
int *ptr = (int *)malloc(sizeof(int) * 2);
ptr[0] = iFirst;
ptr[1] = iSecond;
}
void Test::setNum(int iValue) {
iNum = iValue;
}
int Test::getNum() {
return iNum;
}
int Test::getFirstNum() {
return ptr[0];
}
int Test::getSecondNum() {
return ptr[1];
}
int main() {
Test oTest(3,4);
std::cout << oTest.getFirstNum() << std::endl;
return 0;
}
I just don't understand why I am getting junk value when I try to return ptr[0] using getFirstNum() method. Please enlighten me on how this behaves in memory and possible ways to fix it. Thank youi