Search code examples
c++castingparameter-passingconst-cast

casting const to pass it to function that takes reference, what happens?


Can anyone tell me what happens here when passing to g in the main, is it static_cast?

int  & g (int&x){x++ ; return x ; } 
int main()
{

   const int a=5 ; 
   cout<<g((int&)a)<<endl; 
}

I am sure that no copy is made, since the code above is similar to the one below :

class A
{
public:
    A()
    {
        cout << "calling DEFAULT constructor\n\n";
    }
    A(A& Other)
    {
        cout << "Calling COPY constructor\n\n";
    }
    ~A()
    {
        cout << "Calling DESTRUCTOR\n\n";
    }
};

A& g(A& x)
{
    cout << "Inside g(A& x) \n\n";
    return x;
}

void main()
{
    const A a;
    g(const_cast<A&>(a));
}*/

Thanks in advance :)


Solution

  • static_cast cannot remove constness. This is a const_cast.

    At runtime, this code (the first example) yields undefined behavior because you modify a const object.