Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Const Method Changing its Object

📅 2011-Jan-12 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ const, cpp ⬩ 📚 Archive

A const method cannot directly change its object in C++. But, there is only so much const-checking that can be done at compile time. It is well known that anything can be hacked in C++ using casting and pointers. I was surprised when I inadvertently created a simple const method that changed its object using just a reference:

#include <vector>
using namespace std;

typedef vector<int> IntVec;

class Foo
{
public:
    void method()
    {
        constMethod( _ivec );
    }

    void constMethod( IntVec& iVec ) const
    {
        iVec.push_back( 10 );
    }

private:
    IntVec _ivec;
};

int main()
{
    Foo foo;
    foo.method();

    return 0;
}

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧