# V572. Object created using 'new' operator is immediately cast to another type. Consider inspecting the expression.

The analyzer detected a potential error: an object created by the 'new' operator is explicitly cast to a different type.

For example:

    T_A *p = (T_A *)(new T_B());
    ...
    delete p;

There are three possible ways of how this code has appeared and what to do with it.

1) T_B was not inherited from the T_A class.

Most probable, it is an unfortunate misprint or crude error. The way of correcting it depends upon the purpose of the code.

2) T_B is inherited from the T_A class. The T_A class does not have a virtual destructor.

In this case you cannot cast T_B to T_A because you will not be able to correctly destroy the created object then. This is the correct code:

    T_B *p = new T_B();
    ...
    delete p;

3) T_B is inherited from the T_A class. The T_A class has a virtual destructor.

In this case the code is correct but the explicit type conversion is meaningless. We can write it in a simpler way:

    T_A *p = new T_B();
    ...
    delete p;

There can be other cases when the V572 warning is generated. Let's consider a code sample taken from a real application:

    DWORD CCompRemoteDriver::Open(HDRVR,
      char *, LPVIDEO_OPEN_PARMS)
    {
      return (DWORD)new CCompRemote();
    }

The program handles the pointer as a descriptor for its purposes. To do that, it explicitly converts the pointer to the DWORD type. This code will work correctly in 32-bit systems but might fail in a 64-bit program. You may avoid the 64-bit error using a more suitable data type DWORD_PTR:

    DWORD_PTR CCompRemoteDriver::Open(HDRVR,
      char *, LPVIDEO_OPEN_PARMS)
    {
      return (DWORD_PTR)new CCompRemote();
    }

Sometimes the V572 warning may be aroused by an atavism remaining since the time when the code was written in C. Let's consider such a sample:

    struct Joint {
      ...
    };
    joints=(Joint*)new Joint[n]; //malloc(sizeof(Joint)*n);

The comment tells us that the 'malloc' function was used earlier to allocate memory. Now it is the 'new' operator which is used for this purpose. But the programmers forgot to remove the type conversion. The code is correct but the type conversion is needless here. We may write a shorter code:

    joints = new Joint[n];

This diagnostic is classified as:

CWE-665

You can look at examples of errors detected by the V572 diagnostic.