One of the significant differences between pointers and references is how they can be initialized. It is because of the flexibility of initialization; the pointers are preferred over references in some scenarios. For instance, consider how a pointer can be initialized conditionally:
int x, y;
int* ptr;
// condition is a boolean expression
if(condition) ptr = &x;
else ptr = &y;
// OR
ptr = condition ? &x : &y;
Whereas, when it comes to initializing references conditionally, the things are not as straight forward. Let's take an example. A std::string& rstr is need to be conditionally initialized to std::string X or std::string Y depending on a condition cond. We have 2 logically equivalent implementations A and B below:
Implementation A
std::string X("X"), Y("Y");
std::string& rstr;
if(cond) {
rstr = X;
} else {
rstr = Y;
}
Implementation B
std::string X("X"), Y("Y");
std::string& rstr = cond ? X : Y;
Which of the above implementations is/are valid or will compile successfully? Select the correct answer below and check the Explanations
for details: