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.
The code, as posted, shouldn’t fail, provided you have a virtual function in the base class (as litb pointed out).
But I believe every current compiler generates a ‘Base class is not polymorphic’ kind of error if you hadn’t, so that probably won’t be the problem.
The only thing I can think of is that due to some weird bug everything gets inlined and no vtable gets generated. But if you put the constructor in the C++ file, the compiler decides not to inline everything, triggering the creation of a vtable, causing your cast to work.
But this is very wild guesswork, and I don’t think any compiler would have such a mistake in it (?)
If you want a definite answer, post more code. And the compiler / platform used.
EDIT: Seeing the updated code
I think you should at least derive Derived from Base 😉 (I suppose that’s a typo)
But after seeing the code, the only thing I can think of is that gcc (wrongly) inlines everything and doesn’t generate a vtable for Derived. For what it’s worth, this runs fine compiled with gcc 4.0
3.1 is over 7 years old by now… if there’s any possibility to upgrade I’d go for it.