I recently just lost some time figuring out a bug in my code which was caused by a typo:
if (a=b)
instead of:
if (a==b)
I was wondering if there is any particular case you would want to assign a value to a variable in a if
statement, or if not, why doesn't the compiler throw a warning or an error?
if (Derived* derived = dynamic_cast<Derived*>(base)) {
// do stuff with `derived`
}
Though this is oft cited as an anti-pattern ("use virtual dispatch!"), sometimes the Derived
type has functionality that the Base
simply does not (and, consequently, distinct functions), and this is a good way to switch on that semantic difference.