I was going through a youtube video regarding static in c++, in which I found a piece of code which is confusing me
#include<iostream>
using namespace std;
class Singleton {
static Singleton* s_instance;
public:
static Singleton& Get() { return *s_instance; }
void display() {
cout << "Hello" << endl;
}
};
Singleton* Singleton::s_instance=nullptr;
int main() {
Singleton::Get().display();
}
I wonder why compiler doesn't give an error since we are returning a dereferenced nullptr object in Get() function. Also when I tried the same, but with return type of Get() func set to just Singleton instead of Singleton&, the compiler does throw an error stating that s_instance is a nullptr. Can you explain if the reference return type of Get() func has something to do with this?