Calling const member function in a non-const member function while both of them same function name

38 views Asked by At

class MyClass {
public:
    void Bar()const
    {
        std::cout << "A::Bar() const\n";
    }

    void Bar()
    {
        std::cout << "A::func()\n";
        //call Bar()const in here
    }
};

I would like to know how i should call Bar()const member function in Bar() member function?

1

There are 1 answers

0
NathanOliver On

You need to cast the object to a const qualified version to call the const function. That would look like

void Bar()
{
    std::cout << "A::func()\n";
    const_cast<const MyClass&>(*this).Bar(); // calls const version
}