Why normal constructor won’t do the job and we will need constructor initializer?

Consider the code on the right side of this page

currently it does compile without any errors but
What if we uncomment the constructor which is currently commented and comment the following instead :

//Chart (int & i) : m_xVal{i} {}

Chart (int i)
{
m_xVal = i;
}

Lets compile it to see the following error: 

#include <iostream>
#include <string>
#include <memory>
#include <sstream>
using namespace std;
class Chart
{
public :
Chart (int & i) : m_xVal{i} {}

/*
Chart (int i)
{
m_xVal = i;
}
*/

private :
int& m_xVal;

};

int main ()
{
int k = 9;
Chart myObj(k);
return 0;
}

$g++ wpcpp5.cpp
wpcpp5.cpp: In constructor ‘Chart::Chart(int)’:
wpcpp5.cpp:17:5: error: uninitialized reference member in ‘int&’ [-fpermissive]
17 | Chart (int i)
| ^~~~~
wpcpp5.cpp:24:10: note: ‘int& Chart::m_xVal’ should be initialized
24 | int& m_xVal;
| ^~~~~~

Explanation : 

The reason is that a reference cannot be reassigned. Since we have declared     int& m_xVal; as a reference in our class, it must be initialized at the member-initialization-list. Reference needs to be bound to a variable when the class is constructed. And this is possible through constructor initializer. 

Leave a Comment

Your email address will not be published. Required fields are marked *