I am trying to swap a pointer to point to the address of a new class instance created inside a method, but once back to main, the reference is lost, is this because of scope? Could someone please care to explain? Does c/c++ have reference counting?
#include <iostream>
class MyClass {
public:
int myNum;
std::string myString;
MyClass(int my_num, std::string my_string)
{
myNum = my_num;
myString = my_string;
}
};
void SwapRef(MyClass **p)
{
MyClass b(99, "test");
*p = &b;
}
int main(int argc, char* argv[])
{
MyClass a(1, "main");
MyClass* aPtr = (MyClass*)0;
aPtr = &a;
std::cout << "myNum is: " << aPtr->myNum << " myString is: " << aPtr->myString << "\n";
SwapRef(&aPtr);
std::cout << "myNum is: " << aPtr->myNum << " myString is: " << aPtr->myString << "\n";
#ifdef _WIN32 || _WIN64
system("pause");
#endif
}
OUTPUT:
myNum is: 1 myString is: main
myNum is: -858993460 myString is: