Shouldn't I get an error at line 8 of "main.cpp"?
main.cpp:
#include "stack.hpp"
int main() {
node* firstnode = new node(NULL, 5);
std::cout << firstnode -> getvariable() << std::endl;
node* secondnode = new node(NULL, 10);
std::cout << secondnode -> getvariable() << std::endl;
delete firstnode;
std::cout << firstnode -> getvariable() << std::endl;
return 0;
}
stack.hpp:
#ifndef stack_hpp
#define stack_hpp
#include <iostream>
class node {
public:
node(node* nextnode, int variablevalue);
void setvariable(const int variablevalue);
const int getvariable() const;
private:
node* nextnodelink;
int variable;
};
#endif
stack.cpp:
#include "stack.hpp"
node::node(node* nextnode, int variablevalue)
: nextnodelink(nextnode), variable(variablevalue) {
}
const int node::getvariable() const {
return variable;
}
When you delete an object, the memory that object occupies will be put back to be "available". So that computers run fast, the design of the "make it available" is such that it doesn't do very much other than add the freed object to a linked list or something like that. It doesn't, for example, fill it with nonsense so that it becomes unusable. The point with C++ is that it's fast - to make every delete
fill the object will nonsense just to make sure you can't use it later would slow it down.
Of course, it may be that, if you make some other allocations, the contents of the object is indeed "bad". This is why it's "undefined". The standard doesn't say what will happen, and almost anything CAN happen. Computer catching fire is unlikely, but the C standard doesn't in itself have any wording to say "it must not cause computer to catch fire" or anything of that sort.
A good rule of thumb is that if you want to make your code safe, set the pointer to NULL after you deleted it. That way, your prgram will most likely crash when the pointer is being used.
For example:
delete firstnode;
firstnode = NULL;
std::cout << firstnode -> getvariable() << std::endl;
Now, your program should crash when you call "getvariable". It's not 100% sure to always do that. If you have a function that returns a constant for example, it may still "work".