C++: Const Method Changing its Object

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;
}

2 thoughts on “C++: Const Method Changing its Object

  1. It seems that in constMethod you are changing incoming variable by its reference, so everything is ok in it – your are not touching to _ivec in constMethod.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.