Search code examples
c++classreferencedefault

why would complier allow Initializing a Class with reference member by default constructor


I am learning C++ primer 5th, and know that constructor initializers are required when a class defines reference member otherwise, compiler would complain about it.

However, I wrote a static factory method returing the class with empty statement.

#include <iostream>

using namespace std;

//Learning default initializing values.
class Default {
   public:
    Default(int t) : r(t) {}
    static Default FromDefault() {}

    friend ostream& operator<<(ostream& os, const Default& d) {
        os << "c " << d.c << endl
           << "a " << d.a << endl
           << "b " << d.b << endl
           << "d " << d.d << endl
           << "l " << d.l << endl;
        return os;
    }

   private:
    int& r;  //a reference which require to be initialized
    char c;
    int a;
    float b;
    double d;
    long l;
};

int main() {
    cout << Default::FromDefault();
    return 0;
}

I thought the code won't pass the compiler but it did. As long as I do not use member r, no error would occur.

It seems that a reference class member failed to get initialized and I just wonder why compiler won't find out this error!


Solution

  • FromDefault exhibits undefined behavior, by way of reaching the closing brace without encountering a return statement.


    On an unrelated note, Default(int t) constructor binds the reference r to the local variable. Once the constructor returns, t is destroyed and r becomes dangling. Any attempt to use it afterwards would exhibit undefined behavior.