Take the following struct and class:
struct TestStruct
{
};
class TestClass
{
public:
TestStruct* testStruct;
};
Do the following in main:
TestClass testClass;
if (testClass.testStruct == NULL)
cout << "It is NULL." << endl;
else
cout << "It is NOT NULL.";
The output will be: It is NOT NULL..
However, if I instead do this:
TestClass testClass;
if (testClass.testStruct == NULL)
cout << "It is NULL." << endl;
else
cout << "It is NOT NULL." << endl << testClass.testStruct;
The output will be: It is NULL..
Interestingly enough, if I do this (fundamentally the same as above):
TestClass testClass;
if (testClass.testStruct == NULL)
{
cout << "It is NULL." << endl;
}
else
{
cout << "It is NOT NULL." << endl;
cout << testClass.testStruct;
}
The output will be:
It is NOT NULL.
0x7fffee043580.
What is going on?
Your pointer is not initialized when you declare testClass. You experience here an undefined behaviour. The value of the pointer will be the last value that was contain in the memory section where it is stored.
If you wanted it to always be NULL, you would need to initialize it in the constructor of your class.
class TestClass
{
public:
TestClass(): testStruct(NULL) {}
TestStruct* testStruct;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With