>
>
>
V717. It is suspicious to cast object o…


V717. It is suspicious to cast object of base class V to derived class U.

Analyzer has found a code that utilizes an unusual type cast: pointer to base class object is cast to pointer to derived class, and pointer to base class actually points to the object of base class.

Casting pointers from the derived class to the base class is a typical situation. However, casting pointers from base class to one of its derivatives sometimes can be erroneous. When types were cast improperly, an attempt to access one of derivative' members may lead to Access Violation or to anything else.

Sometimes programmers makes errors by casting a pointer to base class into pointer to derived class. An example from real application:

typedef struct avatarCacheEntry { .... };
struct CacheNode : public avatarCacheEntry,
                   public MZeroedObject
{
  ....
  BOOL   loaded;
  DWORD  dwFlags;
  int    pa_format;
  ....
};
avatarCacheEntry tmp;
....
CacheNode *cc = arCache.find((CacheNode*)&tmp);
// Now on accessing any derived class fields, for instance,
// cc->loaded, access violation will occur.

Unfortunately, it this case it is hard to advice something specific to fix incorrect code - it is likely that refactoring with goals of improving code quality, increasing readability and preventing future mistakes should be required. For instance, if there is no need to access class new fields, it is possible to replace the pointer to the base class with the pointer to derived class.

Code below is considered correct:

base * foo() { .... }
derived *y = (derived *)foo();

The idea here is simple: foo() function actually may always return a pointer to one of classes derived from base class, and casting its result to the derived class is pretty common. In general, analyzer shows V717 warning only in case when it is know that it is pointer exactly to the base class being casted to the derived class. However, analyzer would not show V717 warning in case when there are no new non-static members in the derived class (nevertheless, it is still not good, but it is closer to violation of good coding style rather than to actual error):

struct derived : public base
{
  static int b;
  void bar();
}; 
....
base x;
derived *y = (derived *)(&x);

This diagnostic is classified as: