Say you have a class Foo, and it contains some member variables. And in that class
you have a const-correct function. Can you code some way in C++, that changes the private
member variable, inside the const-correct function. For example :

class Foo{
 int num;
public:
 void doIt()const{
      num = 5; // compile error
  }
}

In other words, can you somehow change num, inside the doIt() function?

Hint, it is possible.

I say no, you need to assign variables in a class in the constructor of the class. PROVE IT!!

Edited 6 Years Ago by LevyDee: n/a

I say no, you need to assign variables in a class in the constructor of the class. PROVE IT!!

I will gladly show you a way. But I want others to take a crack at it to. The solution
I show you will tell you that const-correctness is a guideline, not a strict restriction.

You can do a C-style cast (although the compiler will complain) or a reinterpret_cast of the pointer to one with no const restriction. Or as Agni said, just make it mutable.

One thing that ticks me though... you say "I have a const-correct method".. well putting "const" at the end of the declaration does not make it const-correct, it is not violating that constraint in the implementation that makes it const-correct. Of course const-correctness is a strict rule for those who follow it, you can make the choice not to be const-correct in your code.. but if you do you might run into programmers like myself who are not willing to use open-source code that is not const-correct because it pollutes the open-source software eco-system.

Inside Foo::doIt() you declare a new "this" pointer that is non-const, call it "newThis" then const_cast "this" to get the address of the current object. You then dereference "newThis" to access num and change the value.

Can I show the solution here?

I'm sure it's possible to do it without declaring a new pointer, but, for the sake of readability, I usually prefer to take an extra step where feasible.

Edited 6 Years Ago by Fbody: n/a

Yea I guess you can post it now. Here is what I was talking about:

#include <iostream>

using namespace std;

class Foo{
	Foo *ptr;
	int n;
public:
	Foo(): n(), ptr(this){};
	
	void print()const
	{	cout << n << endl;	}

	void change()const
	{	ptr->n = 10;	}

};

int main(){

	Foo f;

	f.print();
	f.change();
	f.print();
}

I stayed with the doIt() style of the OP. There are 2 different solutions here...

class Foo {
 int num;
public:
 void doIt() const {
   //solution 1:
   Foo *newThis = const_cast<Foo *>(this); //declare a new "this" pointer
   newThis -> num = 5;  //change the value of num

   //solution 2:
   ((Foo *)this) -> num = 10;  //cast "this" directly to a non-const pointer

   //original post:
   //num = 5; // compile error
 }
};

int main() {
	Foo someFoo;

	someFoo.doIt();

	return 0;
}
This article has been dead for over six months. Start a new discussion instead.