Dynamic casting of stack object is not performed

I came across an instance the other day when I had a function, pointing to the base type, which I then needed to add to the derived type to access some additional functions. However, dynamic_castit failed, which was odd because my type definitely inherited the base type.

To understand what was going on, I created the following test program, which, I think, repeats what I saw:

void cast(TestClass *baseType)
{
    if (dynamic_cast<Derived *>(baseType))
        TRACE("cast was sucessful");
    else
        TRACE("cast failed");
}

int main(int argc, char *argv[])
{
    Derived *test1 = new Derived();
    TestClass *test2 = new TestClass();
    TestClass test3;

    test1->identify(); // prints: this is a Derived class
    test2->identify(); // prints: this is a TestClass

    cast(test1); // succesful
    cast(test2); // fail - expected

    // reassign test2 to test1
    test2 = test1;
    test2->identify(); // prints: this is a Derived class

    cast(test2); // succesful

    // the interesting part, the test3 object (created on stack), does not cast
    // despite that it would seem possible from the cast method.
    test3 = *test1;
    test3.identify(); // prints: this is a TestClass
    cast(&test3); // fails?

    return a.exec();
}

, , cast(), , . , ; , . , , , , . , static_cast, ?

+3
1

test3 TestClass (, , Derived), .

*test1, TestClass (aka slicing). , .

, :

*test1:
|--------------|
|TestClass part|
|--------------|
|Derived part  |
|--------------|

test3:
|--------------|
|TestClass part|
|--------------|

(test2=test1), , ( TestClass), .

(test3=*test1), (test3) TestClass, Derived.

+7

All Articles