Jonas
Jonas

Reputation: 7017

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 static_cast and const_cast, but if I use a temp variable everything is fine. It is obviously because the non-const version of bar() calls it self over-and-over. But I though the static_cast would result in a const foo* and then choose the const version of bar(). Why is that so?

#include <iostream>
using namespace std;

class foo
{
    public:
    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;
        tmp.bar();
    }
};

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

Upvotes: 0

Views: 657

Answers (1)

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.

Upvotes: 5

Related Questions