If a pointer is set to NULL wouldn’t any references to it or through it also be NULL. Here is a compilable example that will bomb when you try to run it:
#include <string>
#include <iostream>
#define NULL 0
class Seedcoat {
public:
//Seedcoat();
std::string Name;
int Weight;
};
class Seed {
public:
//Seed();
std::string Name;
int Weight;
Seedcoat* ItsSeedcoat;
};
class Apple {
public:
//Apple();
std::string Name;
int Weight;
Seed* ItsSeed;
};
int main()
{
///////Apple Objects Begin///////
Apple MyApple;
Seed MySeed;
Seedcoat MySeedCoat;
MyApple.ItsSeed = &MySeed;
MyApple.ItsSeed->ItsSeedcoat = &MySeedCoat;
MyApple.ItsSeed->ItsSeedcoat->Weight = 2;
if ( MyApple.ItsSeed != NULL) {
std::cout << "The weight of the apple seed's seedcoat is " << MyApple.ItsSeed->ItsSeedcoat->Weight <<".\n";
}
MyApple.ItsSeed = NULL;
if ( MyApple.ItsSeed->ItsSeedcoat != NULL) {
std::cout << "The weight of the apple seed's seedcoat is " << MyApple.ItsSeed->ItsSeedcoat->Weight <<".\n";
}
return 0;
}
So my question is: Why does this
MyApple.ItsSeed->ItsSeedcoat != NULL
return true. I would think it would not because ItsSeed is set to NULL – but it still tries to reference the weight value of ItsSeedcoat – and then it bombs I presume because ItsSeed does not exist. I realize there are easy ways to get around this – this example was just to show the behavior I am observing. Is this anything to be concerned about? – or is this normal behavior? What is/are the reason(s) it was done this way? Thanks.
C++ does not hold your hand in such a way. Setting a pointer to null sets only that pointer to null. It doesn’t clear any subobjects or free any memory as you might expect in Java or Python.
Once you set the pointer to null, it’s no longer legal to access
MyApple.ItsSeed->ItsSeedcoatso anything could happen.In your particular problem I think composition would probably be a better solution. However if you do need to manage memory allocation/deallocation in C++ I highly suggest using an appropriate smart pointer which gives you power approximately equal to that of garbage collectors in other languages.
I do also suggest not defining
NULLyourself as some headers already define it for C. In C++03 I typically recommend using the literal0while in C++11 you can use thenullptrkeyword.