Skip to content
Related Articles

Related Articles

Improve Article
Can C++ reference member be declared without being initialized with declaration?
  • Difficulty Level : Hard
  • Last Updated : 26 Apr, 2021

To many readers, this might sound the same thing, i.e. 
 

class_type *var = NULL;
*var = &some_work;

is same as

class_type *var = &some_work;

But in actual, it is not. When the declaration and initialization are done at the same step, the compiler calls the copy constructor whereas if done in another step, the compiler calls the default constructor.
To understand this, let’s consider an example:
Example 1: When initialization is not done at the same step of the declaration 
 

CPP




#include <iostream>
using namespace std;
 
class A {
    int& p;
 
    // Note:basically it is
    // supposed to be an error
    // because this reference
    // member p is not initialized
    // with some variable at the same
    // step of its declaration. But it
    // will run in this case. For us,
    // this is the declaration but
    // not for compiler
 
public:
 
    // this line
    // means int &p=w, so p and w
    // both are same. Compiler considers
    // this step as declaration and
    // initialization is done at
    // same step.
    A(int w): p(w)
    {
        cout << p;
    }
};
int main()
{
    A obj(10);
    return 0;
}

Output: 
 

10

Example 2: When initialization is done with the declaration 
 



CPP




#include <iostream>
using namespace std;
 
class A {
    int& p;
 
public:
 
    // In this step,
    // compiler will see only
    // declaration not initialization.
    // Therefore this code will
    // give an error.
    A(int w)
    {
        p = w;
        cout << p;
    }
};
int main()
{
    A obj(10);
    return 0;
}

Compile Errors: 
 

prog.cpp: In constructor 'A::A(int)':
prog.cpp:8:5: error: uninitialized reference member in 'int&' [-fpermissive]
     A(int w)
     ^
prog.cpp:5:10: note: 'int& A::p' should be initialized
     int& p;
          ^

Note: In this code, as soon as an object is created compiler will allocate memory to p by running the constructor of class A. Now as we know reference variable needs to be initialized at the same step so it will pop up an error message called “reference member is not initialized” . 
As we have seen in code 1, initialization is not done at the same step of the declaration, but still, our code runs. But in general, it is a rule that “reference member should be initialized and declared at the same step.”
So the answer to the above question is both yes and no.
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :