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 :(
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 :(
int& d[] = {a,b};
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.
int x = *c[0]+d[1];
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 declare d.
B b[2];
Creates two objects of type B hence calls B() twice.
b[1]=D();
Creates an object of type D. For which it calls constructor of the class itself and its Base class, resulting in calls B() and D(). The created object is stored at array index 1. However since the array is of type B Object Slicing takes place and all the derived members of the object are sliced off. Essentially, the object at b[1] is now of the type B
b[1].print();
Calls print() method on object type B(See explanation above why it is type B)
for the first part see Als's response. The second part:
Question #1
int& d[] = {a,b};
You can't make an array of references. Arrays contain objects. Instances, primitives, and pointers are objects. References aren't.
Question #2, answer elided due to the change in the question.