E2031 Cannot cast from 'type1' to 'type2' (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Compiler Errors And Warnings (C++) Index

A cast from type 'ident1' to type 'ident2' is not allowed.

In C++, you cannot cast a member function pointer to a normal function pointer.

For example:

class A {
public:
   int myex();
};
typedef int (*fp)();
test()
{
   fp myfp = (fp) &A::myex; //error
   return myfp();
}

The reason being that a class member function takes a hidden parameter, the this pointer, thus it behaves very differently than a normal function pointer.

A static member function behaves as normal function pointer and can be cast.

For example:

class A {
public:
   static int myex();
};
typedef int (*fp)();
test()
{
   fp myfp = (fp) &A::myex; //ok
   return myfp();
}

However, static member functions can only access static data members of the class.

In C

  • A pointer can be cast to an integral type or to another pointer.
  • An integral type can be cast to any integral, floating, or pointer type.
  • A floating type can be cast to an integral or floating type.

Structures and arrays can't be cast to or from.

You usually can't cast from a void type.

In C++

User-defined conversions and constructors are checked for. If one can't be found, the preceding rules apply (except for pointers to class members).

Among integral types, only a constant zero can be cast to a member pointer.

A member pointer can be cast to an integral type or to a similar member pointer.

A similar member pointer points to a data member (or to a function) if the original does. The qualifying class of the type being cast to must be the same as (or a base class of) the original.