← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 10 of 17

C++ const_cast

What is const_cast?

The const_cast operator is used to add or remove the const qualifier from a variable. It is primarily used to pass const pointers or references to legacy functions that accept non-const parameters.

Example: What is const_cast?

cpp
#include <iostream>

void legacyPrint(char *msg) {
	std::cout << msg << std::endl;
}

int main() {
	const char *text = "Hello";
	legacyPrint(const_cast<char *>(text));
	return 0;
}

Modifying const References

If an original variable was declared as non-const, you can pass it to a function as a const reference, and then use const_cast inside the function to temporarily modify its value.

Example: Modifying const References

cpp
#include <iostream>

void modify(const int &x) {
	int &writable = const_cast<int &>(x);
	writable = 100;
}

int main() {
	int value = 5;
	modify(value);
	std::cout << value << std::endl;
	return 0;
}

Undefined Behavior Warning

You must never use const_cast to modify a variable that was originally declared as const. Doing so causes Undefined Behavior, which can corrupt memory or crash your program.

Example: Undefined Behavior Warning

cpp
#include <iostream>

int main() {
	const int value = 10;
	int &ref = const_cast<int &>(value);
	// ref = 20; would be undefined behavior: value was truly const
	std::cout << "Never modify a truly const original" << std::endl;
	return 0;
}

const_cast in Overloaded Methods

A common use for const_cast is to avoid code duplication when overloading member functions for both const and non-const objects. You can implement the non-const method by reusing the const version's logic.

Example: const_cast in Overloaded Methods

cpp
#include <iostream>

class Data {
	int value = 5;
public:
	const int &get() const { return value; }
	int &get() {
		return const_cast<int &>(static_cast<const Data &>(*this).get());
	}
};

int main() {
	Data d;
	d.get() = 42;
	std::cout << d.get() << std::endl;
	return 0;
}

const_cast Alternatives

Before using const_cast, consider alternative solutions. If you need to modify a class member variable inside a const function, declare that member variable with the mutable keyword instead.

Example: const_cast Alternatives

cpp
#include <iostream>

class Cache {
	mutable int hits = 0;
public:
	void access() const { hits++; }
	int getHits() const { return hits; }
};

int main() {
	Cache c;
	c.access();
	std::cout << c.getHits() << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.