who can explain? (reference)

#include <iostream>

void func1(int &a);
void func2(const int &a);

int main()
{
double d = 5.5;
//func1(d); error,,, why?
func2(d); // no error,,, why?
return 0;
}

void func1(int &a)
{
std::cout << a << std::endl;
}

void func2(const int &a)
{
std::cout << a << std::endl;
}
//func1(d); error,,, why?

d is not an int. The compiler can't create a temporary int to feed to the function because a non-const reference will not bind to a temporary.


func2(d); // no error,,, why?

In this case the compiler can create a temporary int to feed to the function because a const reference will bind to a temporary.
thank you cire,,, but why a non-const reference will not bind to a temporary and a const reference will bind to a temporary?
closed account (o1vk4iN6)
Modifying a temporary value doesn't make sense, it's to help prevent errors that can be caused by accidentally modifying a value that otherwise has no meaning being modified.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

void func1(int &a)
{
    a = 10;
}

int main()
{
    double foo = 0;

    func1(foo); // if this was legal

    std::cout << foo; // outputs 0

}
Last edited on
thanks a lot xerzi
Topic archived. No new replies allowed.