From my knowledge 1 and 2 are similar, but 2 is not creating another object when it's being passed. With that same logic, why isn't 4 not a valid declaration because I assumed it would be similar to 3. Is the 5th snippet similar to 3, since it's an integer pointer to a object's address, which I would assume is the same as int * a
4) constint*& is a reference to a non-const pointer to a const int.
A reference to a const can be used to refer to both const and non-const objects. That's why you can pass integer literals and also integer variables to function 2.
1 2 3 4
void test(constint&);
int x = 10;
test(x); // this works because a const int& can refer to a non-const int.
test(5); // this would not have worked if test was declared as void test(int&).
A reference to non-const can only refer to non-const objects. That means function 4 only accepts non-const pointers.
1 2 3 4 5 6 7
void test(constint*&);
constint* nonConstPointerToConstInt = nullptr;
test(nonConstPointerToConstInt); // Works fine.
constint* const constPointerToConstInt = nullptr;
test(constPointerToConstInt); // This does not work because the pointer is const.
When you have references to pointers it is also important to note that the type being pointed to need to match exactly. That means you can not have a reference to a pointer to a const int that refers to a pointer to non-const int.
int *a; //pointer to integer
a = nullptr; //modify the pointer, valid
*a = 42; //modify what is points to, valid
constint *b; //pointer to constant integer
b = nullptr; //valid
*b = 42; //illegal
int * const c = nullptr; //constant pointer to integer
c = nullptr; //can't modify a constant, illegal
*c = 42; //valid
constint * const d = nullptr; //constant pointer to constant integer
d = nullptr; //illegal
*d = 42; //illegal
a reference must bind to a variable, a constant reference may bind to a r-value.
1 2 3 4 5 6 7 8
void foo(int &a);
void bar(constint &a);
int n = 42;
foo(n);
foo(42); //illegal
bar(n);
bar(42);
> why isn't 4 not a valid declaration
so now, ¿can you come up with a valid example for (4)?
That's not entirely true. If the passed paramter can be referenced the reference is used otherwise an object will be created and the appropriate constructor will be called.
In Peter87's example x can be referenced while 5 not. So in the first case no object will be created in the second case it will.
why isn't 4 not a valid declaration It is perfectly valid.