Implicit conversion regarding constness in c++

Report
Question

Please briefly explain why you feel this question should be reported .

Report Cancel
#include <iostream>
int foo(const char* keke) {
  std::cout << keke;
  return 0;
}
int main()
{
  char* keke = new char(10);
  char* const haha = keke;
  return foo(haha);
}

Why there is no any errors/warning while compiling the above code?

The type of haha is char* const, while foo only receive argument of type const char*. Could char* const implicit convert to const char*?

solved 0
1 Answer 8 views 0

Answer ( 1 )

    4
    January 12, 2017 at 7:00 am

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    Yes. It’s called qualification conversions (one of the implicit conversions):

    (emphasis mine)

    A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).

    “More” cv-qualified means that

    a pointer to unqualified type can be converted to a pointer to const;

    It means char* could be implicitly converted to const char*.

    const qualifier on the pointer itself doesn’t matter here, the parameter keke itself is declared to be passed by value, it’s fine the argument to be copied from haha (i.e. the const pointer; char* const).

    Best answer

Leave an answer

Browse

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>