As per Scott Meyers, to prevent repetition of code in the const version of a getter and the non-const version of a getter, call the const version of the method from the non-const version: static_cast<const A&>(*this).Methodology();
however, in accidental usage due to an overzealous Visual Assist X Intellisense I typed: const_cast<const A&>(*this).Methodology();
and it worked just fine.
What are any and all differences in this case with using a particular cast?
IDE in use: Visual Studio 2010.
After re-reading Item 3 from
Effective C++ 3rd Ed.
I realize that he was actually advocating using both. Add const to call the const version, then cast away the const-ness of the return value (if there is one). In my particular case, there is no const return value, just a const-function so the wrapped-by-const_cast<> version is not needed and in effect causes there to be no difference between the two calls in questionAssuming that the type of
this
isA*
, there is no difference.In general
const_cast
can cast aways theconst
specifier (from any level of indirection or template parameter)static_cast<>
can cast a type to another if the target type is in the source's type hierarchy.They cannot do each other's work.
The reason they both worked in your case is because you have introduced const-ness, as opposed to having taken it away (calling from the non-const version of the function the type of
this
isA*
, no const). You could just as well have writtenand it would have worked without the need for any casting. The casting is used for convenience and terseness to not have to introduce a new variable.
Note: you can use
static_cast<>
here as you know that you are casting to the right type. In other cases (when you cannot be sure) you need to usedynamic_cast<>
that does a runtime type check to ensure the conversion is valid