Jonas Jonas - 1 year ago 64
C++ Question

Why does a const_cast (or static_cast) not add const?

I was looking at this answer and wanted to use. However, I get a

Segmentation fault
, when using the
, but if I use a temp variable everything is fine. It is obviously because the non-const version of
calls it self over-and-over. But I though the
would result in a
const foo*
and then choose the const version of
. Why is that so?

#include <iostream>
using namespace std;

class foo
void bar() const
cout << "const" << endl;

void bar()
cout << "non-const" << endl;

// static_cast<const decltype(this)>(this)->bar();

// const_cast<const decltype(this)>(this)->bar();

const auto& tmp = *this;;

int main() {
foo A;;
const foo B;;
static_cast<const foo*>(&A)->bar();
return 0;

I have confirmed the behaviour using the following compilers:

  • Debian clang version 3.5.0-10

  • g++ (Debian 4.9.2-10)

  • g++ 5.1 (

Answer Source

decltype(this) is foo*. And const decltype(this) is foo* const.

You don't change the pointees cv-qualifications, only the pointers. Therefore the non-const overload is chosen every time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download