Why is casting required here? 
Author Message
 Why is casting required here?

The following snippet of code:

    class base{};
    class derived : public base{};

    class container{
    private:
     derived* derived__;
    public:
     derived& element();
    };

    derived&
    container::element()
    {
      return *derived__;
    }

    base& ( container::* method ) ( void ) = container::element;

generates the following error on the last line:
  error C2440: 'initializing' : cannot convert from
  'class derived &(__thiscall container::*)(void)' to
  'class base &(__thiscall container::*)(void)'

It appears to me that there is sufficient information available for this to
work. Is there an explanation why this error is generated? Is there a better
way to make this work than to use a cast? (MS VC++ 6 SP3)

John Keenan



Sat, 26 Feb 2005 10:11:03 GMT  
 Why is casting required here?
On Mon, 9 Sep 2002 21:11:03 -0500, "John Keenan"

Quote:

>The following snippet of code:

>    class base{};
>    class derived : public base{};

>    class container{
>    private:
>     derived* derived__;
>    public:
>     derived& element();
>    };

>    derived&
>    container::element()
>    {
>      return *derived__;
>    }

>    base& ( container::* method ) ( void ) = container::element;

>generates the following error on the last line:
>  error C2440: 'initializing' : cannot convert from
>  'class derived &(__thiscall container::*)(void)' to
>  'class base &(__thiscall container::*)(void)'

>It appears to me that there is sufficient information available for this to
>work. Is there an explanation why this error is generated? Is there a better
>way to make this work than to use a cast? (MS VC++ 6 SP3)

Using the cast gives undefined behaviour. Basically, the only
conversion allowed for member function pointers is:

T (Base::*)(params) to T (Derived::*)(params)

The cast you are doing is changing the return type of the function,
and therefore can't work.

Rather than mess around with function pointers, consider using a
callback library like boost.function. See www.boost.org

Tom



Sat, 26 Feb 2005 18:58:57 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Newbie very puzzled - no cast required??

2. Help with structure element casting required

3. casting for varargs required?

4. Why am I getting an ExecutionEngineException?

5. why require oleacc.dll?

6. Why am I being ignored ???

7. Why am I seeing such a delay between my catch block and my finally block

8. Macro with functions problem -- why am I stupid?

9. Why am I not getting correct position?

10. Why am I getting a segmentation fault?

11. Why am I not intercepting Enter key (VK_RETURN)

12. ODBC cursors required for snapshot support, why?

 

 
Powered by phpBB® Forum Software