I have a base class and a derived class. Each class has an .h file and a .cpp file.
I am doing dynamic_cast of the base class object to the derived class in the following code:
h files:
class Base
{
public:
Base();
virtual ~Base();
};
class Derived : public Base
{
public:
Derived(){};
void foo();
};
class Another
{
public:
Another(){};
void bar(Base* pointerToBaseObject);
};
cpp files:
Base::Base()
{
//do something....
}
Base::~Base()
{
//do something....
}
void Derived::foo()
{
Another a;
a.bar(this);
}
void Another::bar(Base* pointerToBaseObject)
{
dynamic_cast<Derived*>(pointerToBaseObject)
}
From some strange reason, the casting fails (returns NULL). However, the casting succeeds if I move the implementation of Derived class's constructor from .h to the .cpp file.
What can cause it?
The compiler is gcc 3.1, on Linux-SUSE. BTW, I see this behavior only on this platform, and the same code works fine in Visual Studio.
If a dynamic_cast fails, the result of the conversion will be a null pointer. Because we haven't checked for a null pointer result, we access d->getName(), which will try to dereference a null pointer, leading to undefined behavior (probably a crash).
As we learnt in the generic types example, static_cast<> will fail if you try to cast an object to another unrelated class, while reinterpret_cast<> will always succeed by "cheating" the compiler to believe that the object is really that unrelated class.
dynamic_cast will no longer throw an exception when type-id is an interior pointer to a value type, with the cast failing at runtime. The cast will now return the 0 pointer value instead of throwing.
If the cast is successful, dynamic_cast returns a value of type new-type. If the cast fails and new-type is a pointer type, it returns a null pointer of that type. If the cast fails and new-type is a reference type, it throws an exception that matches a handler of type std::bad_cast.
Do you have any virtual function in Base? It won't work otherwise. If nothing else, make its dtor virtual.
Don't know whether it was already asked by the other guy that deleted his answer, but i believe it was something different: Are you doing the dynamic_cast from the bases' constructor? If so, that won't work. The compiler will think that the Base is the most derived type, similar to when you call a virtual function and it ends up calling the version of the Base.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With