Static_cast and Const_cast in C++
This is a note for Lecture 8, CS106L, Spring 2023.
In a class like this:
1 | class StrVector { |
We implement the non-const at
method like this:
1 | std::string& StrVector::at(size_t index) { |
It is bad to reimplement the same logic when writing the const version of the at
method.
1 | // bad |
Instead, we should do this:
1 | const std::string& StrVector::at(size_t index) const { |
So, what's static_cast
and const_cast
?
static_cast<new-type>(expression) is used to convert from one type to another. For example: int my_int = static_cast<int>(3.1)
. Note that it CANNOT BE USED WHEN conversion would cast away constness.
Learn more here
const_cast<new-type>(expression) is used to cast away (remove) constness. It allows you to make non-const pointer or reference to const-object like this:
1 | const int const_int = 3; |
Learn more here