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.
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.