1 2
|
Human* firstMan; // gives me an error
firstMan->name = "Adam";
|
|
What error does the
Human* firstMan;
generate?
Another compiler
warns about the next line:
In function 'int main()':
22:17: warning: 'firstMan' is used uninitialized in this function [-Wuninitialized] |
A warning is not an error that would prevent compiling code, although in this case it points out fatal logical error.
You create a variable 'firstMan' that is a pointer, but you don't set it to point to any Human objects.
In
firstMan->name
you dereference the pointer in order to access the object that it points to.
Alas, your pointer does not point to any human!
Then you write to member of an object that does not exist. You write to memory that is not what you believe it is. You overwrite something that might be important. It is like I would park my Monster Truck blindfolded; completely ignoring where I am or what else is there.
As said, the OS reclaims all memory allocated for process when the process ends, but relying on that is a bad habit that you don't want to learn. If you wan't to use
new
, then you should use the
delete
too, appropriately. Truth is, all that is so tedious that you should transit to "smart pointers" and "containers" that do the menial chores on your behalf.