Walidix Walidix - 1 year ago 137
C++ Question

C++ Reference intialization

I'm confused with the reference initialization in C++.
Normally reference should be initialized when it is declared but I found that when it is a class member reference is declared without being initialized.

It is a special case?

What is the correct rule?

Answer Source

This rule still applies, reference as member variable you have to initialize in constructor-s initilization list. Example:

class X {
    X(int& ri) : mri(ri) {}
    // X()  {} // ERROR! no explicit initialization of mri
    int& mri; 

int main() {
    int i;
    X x(i);

without initilizing it you will get compiler error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download