I have some class code that had data members on the stack I was modifying to be constructed on the heap. Original (simplified) code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <string>
using ushort_t = unsigned short;
class Human
{
private:
std::string Name;
ushort_t Age;
public:
// constructor
Human();
// destructor
~Human();
public:
void SetName(std::string HumansName) { Name = HumansName; }
void SetAge(ushort_t HumansAge) { Age = HumansAge; }
void IntroduceSelf();
};
int main()
{
Human FirstMan;
FirstMan.SetName("Adam");
FirstMan.SetAge(30);
Human FirstWoman;
FirstWoman.SetName("Eve");
FirstWoman.SetAge(28);
std::cout << '\n';
FirstMan.IntroduceSelf();
FirstWoman.IntroduceSelf();
std::cout << '\n';
}
Human::Human()
{
std::cout << "Constructing an instance of class Human\n";
Name = "";
Age = 0;
}
Human::~Human()
{
std::cout << "Destroying an instance of class Human\n";
}
inline void Human::IntroduceSelf()
{
std::cout << "I am " + Name << ", and I am " << Age << " years old.\n";
}
|
So far so good, stack version compiled fine, ran great, less filling, etc.
After several botched attempts to change the Age data member to be on the heap I finally got a version that compiled, and ran. Somewhat. Age was being reported as 0. *scratches head*
I had changed SetAge to this:
void SetAge(ushort_t HumansAge) { Age = &HumansAge; }
Win 10 reports non-critical errors with programs, and every time I ran the .exe another error report was generated.
OK, I definitely needed some coffee while I tried to figure out what was going wrong.
Two cups later, *BOING!*
void SetAge(ushort_t HumansAge) { *Age = HumansAge; }
The moral is:
No Coffee, Make Stupid Mistakes
I know there are other issues with the code, such as the constness of the getter.