Tuesday, June 4, 2013

Article 1: Implicit Conversion for const and non-const reference.

#include <iostream>

/*

*Problem:     
Implicit conversion will not work for non const reference.
*Description:
Read the comments above each method call.
*Proof:     
Print address of each variable which is passed as an argument, the address will be same for foo2(), foo3() but will be different for foo1(),and foo() will not be called anyways(compilation error)
*/



void foo(const double& f)
{
    std::cout<<"\nConst Reference Function called. "<<&f;
}

void foo1(double& f)
{
    std::cout<<"\nNormal Reference Function called "<<f;
}

void foo2(int& i)
{
    std::cout<<"\nNormal Reference Function called for int. "<<&i;
}

void foo3(const int& i)
{
    std::cout<<"\nConst Reference Function called for int. "<<&i;
}

int main()
{
    int i = 10;
    std::cout<<"\nInitial Address of i "<<&i;
    // This will work as i local copy will be created as double and that can be access as a const value.
    foo(i);
   
    // This function will give an error as if it create a local variable double which is passed as reference,
    // it shows that this method can change the value, which is not possible.
    // error C2664: 'foo1' : cannot convert parameter 1 from 'int' to 'double &'
    foo1(i);

    // This is called without any issue.
    foo2(i);

    // This is called without any issue.
    foo3(i);
    std::cout<<"\n";
   

}
Output:
Initial Address of i 0025FE9C
Const Reference Function called. 0025FDCC
Normal Reference Function called for int. 0025FE9C
Const Reference Function called for int. 0025FE9C

No comments:

Post a Comment