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.

Dani AI

Generated

Short answer: yes — but only with explicit language support or by casting away const, and each approach has tradeoffs.

pointed to the cleanest, standard way: declare the member you intend to mutate as mutable. That preserves “logical constness” (the object’s observable state remains the same) while allowing internal caches, lazy initialization, counters, or synchronization primitives to change inside const member functions. For example:

class Counter {
    mutable int cachedValue{-1};
public:
    int value() const {
        if (cachedValue == -1) {
            // expensive calculation
            cachedValue = 42; // allowed because cachedValue is mutable
        }
        return cachedValue;
    }
};

and correctly noted casting tricks (C-style cast or const_cast) can remove const, but this is only safe if the object was not originally declared const — modifying a truly const object after removing constness is undefined behavior (see const_cast). The pointer-to-this technique shown by works around the language too, but it is brittle: storing this as a member breaks copy/assignment semantics (copied objects will have a pointer that still points at the original) and is error-prone.

Typical guidance: prefer mutable when the change is not part of the object’s external state (caches, memoization, a mutable std::mutex for locking in const methods). Avoid casting away const or embedding this unless interacting with legacy APIs or very low-level code. For rules and guarantees see the standard references and the mutable description on cppreference: .

Recommended Answers

All 7 Replies

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

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.

We could declare it as mutable.

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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.