static_cast raises an error bcos of const?

hi,

POSITION pos =controlBars().GetHeadPosition();
  while(pos!=NULL)
  {
   CToolBar* bar =DYNAMIC_DOWNCAST(CToolBar, static_cast<CControlBar*>(controlBars().GetNext(pos)));
   
   //some code
  }

where

const CPtrList& controlBars();

is the declaration of the controlBars().

I am getting an error as below

'static_cast' : cannot convert from 'const void *' to 'CControlBar *'

This compiles fine in VC 6.0. But the above error is displayed in VC 8.0.

Any workaround for this Is it because of the "const" bcos when i remove it,
compilation is successful. Even in that case why does it work in VC 6.0 and not
in VC 8.0

regards,
sk80.



Answer this question

static_cast raises an error bcos of const?

  • dmkelly10

    hi OShah,

    thanks for your reply.

    regards,

    sk80.

     

     


  • Tom_HDi

    5.2.9/1 of the C++ standard demands that static_cast shall not cast away constness.

    In MFC 6, the definition of const CPtrList::GetNext() was

    void* GetNext(POSITION& rPosition) const; // return *Position++

    Notice that the void * is modifiable (and can possibly be used to alter the const object). Somewhere between MFC4.2 and MFC7.1, the CPtrList class was changed so that items in const CPtrLists could not be altered. One change was the following:

    const void* GetNext(POSITION& rPosition) const; // return *Position++

    const CPtrList::GetNext now returns a const void*. Now, you're attempting to static_cast a const void (forbidden by the C++ standard, hence the error).

    If you are just reading from the CPtrList, I suggest upgrading the code so it becomes const friendly. If you are actually modifying the contents of the CPtrList, then you'll have to remove the const from the CPtrList.

     



  • static_cast raises an error bcos of const?