I have once asked this question and after hours of research I think the answers are not suitable and do not fix my issue. Please inspect this code:
#include <iostream>
using namespace std;
class Test
{
public:
Test();
Test(int);
~Test();
friend Test Problem();
int get_a ();
private:
int* a;
};
Test::Test(int x)
{
a = new int[1];
*a = x;
}
Test::~Test()
{
delete [] a;
}
Test Problem()
{
Test doomed(1);
int* doomed_too = new int[1];
*doomed_too = 99;
doomed.a = doomed_too;
return doomed;
}
int Test::get_a()
{
return *a;
}
int main()
{
Test Sniffer = Problem();
if (Sniffer.get_a() == 99) cout << "You saved me! Thanks!";
return 0;
}
Yes, I know that object doomed will be destroyed before returned to object Sniffer, so Sniffer will get random value from the freed memory of the Heap. My issue is - how to save the "life" of this object doomed? Can you provide working code/"fix"?
Furthermore, I know this specific example has many workarounds but on the project I am working on I am not allowed to do such workarounds (no strings, no vectors, just dynamic array of ints without using further libraries and complications).
I will be glad if you can test your solution first (before answering).
I did lot of research on this topic and I am amused that all the lectures and examples always use not-dynamic private members or if they use in their examples dynamic private members they always "skip" to show operator+ overloading or operator* overloading (just examples).
How can we make operator+ overloading public-member function of a given Class, if the same Class do posses a dynamic private-member - for example int* n?