class Test{
int &b; // no error, can compile
};
int main() {
int &b; // error: 'b' declared as reference but not initialized
}
Why I cant have int &b in main function, but can have it in Test class?
class Test{
int &b; // no error, can compile
};
int main() {
int &b; // error: 'b' declared as reference but not initialized
}
Why I cant have int &b in main function, but can have it in Test class?
A reference must be bound to something at the point where it starts existing.
In the class the declaration specifies that each instance of the class should have this reference. Each such reference starts existing when its class instance is created. At that point some constructor in the class must initialize it, via the constructor's member initializer list, if the reference hasn't been initialized in the declaration (and yours wasn't).
In the function the reference starts existing as the execution passes the declaration. Therefore it must be initialized at this point.
You can't have a reference that doesn't point to anything. Simply defining a class doesn't actually instantiate one; had you tried to create a Test
you would have found that would fail as well.
Reference variables need an initializer. Local variables are initialized at the point of declaration. Member variables are initialized in the member initialization list.