Dynamic_cast not working

I have a base class and a derived class. Each class has a .h file and a .cpp file.

I am doing a dynamic_cast of a base class object to a 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)
}

For some strange reason, casting fails (returns NULL). However, casting succeeds if I move the Derived class constructor implementation from .h to the .cpp file.

What can cause this?

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.

+5
source share
6 answers

The code, as indicated, should not fail if you have a virtual function in the base class (as indicated in the shortcut).

, "Base class is not polymorphic", , , , .

, , , - - , vtable . ++, , vtable, .

, , - (?)

, . /.

EDIT:

, Derived from Base;) ( , )

, , , gcc () vtable Derived. , gcc 4.0

3.1 7 ... , .

+5

? . , dtor .

, , , , - : dynamic_cast ? , . , Base - , , , , Base.

+7

(, , ) .cpp.

(read: gcc) - . .cpp, .

dynamic_cast. , , .

, , , , , ( ). .

+3

Visual ++? , (RTTI) , .

, , . , ++!!!

0

. ? .

0

, , Derived Base.

: FYI, g++ 3.4.5

0

All Articles