FileSystem() always returns NULL yet I can still call the functions of EngineFile through g_System->FileSystem()->;
I've tested this on VS2017 and one online compiler.
Obviously my intention is not to actually leave FileSystem() returning NULL because it was intended that Systems.ef get set to the EngineFile pointer. In a project I'm working on I accidentally forgot to ever set the pointer and when stepping through some other code I realized it was just returning NULL and it was still working.
I have condensed it down to a single file so all the code is right there.
Why does this work and how?
#include <iostream>
using namespace std;
class EngineFile
{
public:
EngineFile();
~EngineFile();
const char* GetFileData(const char* filename);
void ModifyBool(void);
private:
bool testmodify = false;
};
EngineFile::EngineFile()
{
}
EngineFile::~EngineFile()
{
}
void EngineFile::ModifyBool(void)
{
testmodify = true;
}
const char* EngineFile::GetFileData(const char* filename)
{
// open file filename
// stub function basically
return "This is the file data\n";
}
class Systems
{
public:
Systems();
~Systems();
EngineFile* const FileSystem(void);
private:
EngineFile* ef = NULL;
};
Systems::Systems()
{
}
Systems::~Systems()
{
}
static Systems* g_System;
EngineFile* const Systems::FileSystem(void)
{
return ef;
}
int main()
{
EngineFile* ef = new EngineFile();
g_System = new Systems();
// calling the function directly works as we would think
cout<<ef->GetFileData("test.txt");
// calling it through indirection with FileSystem returning NULL works
// why does this work? I feel like it should not work
cout << g_System->FileSystem()->GetFileData("test.txt");
// this will return null to show FileSystem returns null
EngineFile* efnulltest = g_System->FileSystem();
if (efnulltest == NULL)
cout << "efnulltest is NULL\n";
cout << "some extra text to show previous statement is still working\n";
// segfault as expected
g_System->FileSystem()->ModifyBool();
return 0;
}