I recently learned about the difference between the heap and the stack in c++, and how the stack is much more efficient and so should be used over the heap when possible. When I looked to see why one would want to ever use the heap, I saw this question, which said to use the heap when a variable is needed beyond a function's scope.
Example:
#include <iostream>
int* giveNumPtr()
{
int* num = new int;
*num = 10;
return num;
}
int main()
{
int* val = giveNumPtr();
std::cout << *val << std::endl;
*val = 3;
std::cout << *val;
}
However, can't this be accomplished just as well on the stack?:
#include <iostream>
int* giveNumPtr()
{
int num;
num = 10;
return #
}
int main()
{
int* val = giveNumPtr();
std::cout << *val << std::endl;
*val = 3;
std::cout << *val;
}
What am I missing, and what are the benefits of doing it the first way on the heap?