Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a const variable as reference

At some places I have seen variables declared like this

const int &var1;
extern int & var2;

These variables are defined somewhere else. I always thought that when you declare a reference to a variable you bind the reference to that variable at the same place. I am missing something here. Also I have not seen references declared as above when there is no qualifier (e.g. const or extern).

like image 803
polapts Avatar asked Aug 10 '26 05:08

polapts


1 Answers

const int &var1;

this is illegal if not part of a class or a struct. If it is, it must be initialized in the constructor initializer list.

The reason it's legal is because the variable doesn't exist until an object of that class is created. So there's no unbound reference, as there is no reference to speak of.

like image 158
Luchian Grigore Avatar answered Aug 11 '26 21:08

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!