dynamic_cast won't compile that I have to have at least one virtualmethod

S

srdgame

Below is my testing code, and it won't be compiled successfully, unless
you uncomment the "virtual void f(){}".

I wanna to know is this required by C++ Standard, or just because of GCC?

struct A
{
//virtual void f(){}
};
template <class T>
struct TA : public A
{
T _t;
};

int main()
{
A* a = new TA<int>();
TA<int>* ta = dynamic_cast< TA< int >* >(a);

delete a;
}

thanks
srdgame
 
I

Ian Collins

srdgame said:
Below is my testing code, and it won't be compiled successfully, unless
you uncomment the "virtual void f(){}".

I wanna to know is this required by C++ Standard, or just because of GCC?

wanna?

dynamic_cast can only be used on polymorphic objects, so yes, at least
one virtual method is required.
 
S

srdgame

于 Sat, 21 Mar 2009 15:43:43 +1300,Ian Collins写到:
wanna?

dynamic_cast can only be used on polymorphic objects, so yes, at least
one virtual method is required.

Thanks for your reply. I have to give up to use dynamic_cast, and trun
to static_cast. What is pity!

srdgame
 
S

SG

Sat, 21 Mar 2009 15:43:43 +1300,Ian Collins:

Thanks for your reply.  I have to give up to use dynamic_cast, and trun
to static_cast.  What is pity!

You shouldn't. You NEED polymorphism here for the destructor.
Otherwise you get undefined behaviour ("delete a") because a is of
type A* but it points to an object of type TA<int>. You need to
write:

struct A
{
virtual ~A(){}
};

to make it work.

Cheers!
SG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top