I have this simple piece of code :
int a = 1, b = 2;
int* c[] = {&a,&b};
int& d[] = {a,b};
int x = *c[0]+d[1];
If the following works
int &d = a;
I can’t understand why the line 3 and 4 generates an error. :-s
It really makes no sense to me 🙁
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You cannot create an array of references. It is not allowed by the C++ Standard.For it to be allowed the entire type mechanism would have to be re-written.
Gives you an error because the compiler cannot make out the type of
d, since there is a compilation error on the previous line where you declared.Creates two objects of type
Bhence callsB()twice.Creates an object of type
D. For which it calls constructor of the class itself and its Base class, resulting in callsB()andD(). The created object is stored at array index1. However since the array is of typeBObject Slicing takes place and all the derived members of the object are sliced off. Essentially, the object atb[1]is now of the typeBCalls
print()method on object typeB(See explanation above why it is typeB)