views:

80

answers:

1

I am using Visual Studio 2003 to compile and run following program.

There are 4 assignment operation where I expect 2 of them to run ok and 2 of them to raise exception. There is a dynamic casting inside overloaded = operator which expect to fail during non proper cross casting (Casting from Apple to Orange or Orange to Apple). But in my case all the 4 operations are failing ( Raising exception ). I have run the same code in Visual Studio 2008 and it is working fine as expected. But moving entire project to Visual Studio 2008 is difficult. Is this a problem of Visual Studio 2003? If so, is there any way to fix this?

Note: class Fruit is read only and cannot be changed.

class Fruit
{
public:
    virtual void operator = ( const Fruit& fruit )
    {
    }
};

class Apple : public Fruit
{
public:
    virtual void operator = ( const Fruit& fruit )
    {
     Apple& apple = dynamic_cast<Apple&>( fruit );
    }
};

class Mango : public Fruit
{
public:
    virtual void operator = ( const Fruit& fruit )
    {
     Mango& mango = dynamic_cast<Mango&>( fruit );
    }
};

int main( void )
{
    Apple apple;
    Mango mango;
    Fruit* fruit[] = { &apple, &mango };

    *fruit[0] = *fruit[0]; /* Expect to work ok */
    *fruit[0] = *fruit[1]; /* Expect an exception */
    *fruit[1] = *fruit[0]; /* Expect an exception */
    *fruit[1] = *fruit[1]; /* Expect to work ok */
}
+2  A: 

You need to check Enable Run-time type information (RTTI) in Project Settings. Category "C++ Language".

In VC6 at least it will not be enabled by default.

aJ
If the parent class was compiled to a library without RTTI turned on, and you can't recompile it, you may be out of luck.
Mark Ransom
It works man... Thanks a lot aJ.......... :)
Vadakkumpadath