Function Overloading In C++ - why is const disregarded in the first example but not in the second?

Consider the following bits of code:

void foo(const int i) // First foo
{
   std::cout << "First " << i << endl;
}

void foo(int i)       // Second foo
{
   std::cout << "Second " << i << endl;
}

int main() 
{
   int i = 5;
   foo(i);      
}

Redefinition of ‘void foo(int)’ causes a compilation error.

Because consts can be initialised with non-const objects, the preceding behaviour appears to be logical. Consider the following:

void foo_ptr(const int* p)  // First foo_ptr
{
   std::cout << "First " << *p << endl;
}

void foo_ptr(int* p)        // Second foo_ptr
{
   std::cout << "Second " << *p << endl;
}

int main()
{
   int i = 5;
   foo_ptr(&i);             // Second foo_ptr gets called; prints 'Second 5'
}

As you may have guessed, my query is if the two definitions of foo in the first example are regarded equivalent, why isn’t the same true for foo ptr in the second? In other words, why is const disregarded in the first example but not in the second?

1 Like

Corresponding tweet for this thread:

Share link for this tweet.