# Virtual inheritance and dynamic_cast

This topic is 4415 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am toying around with some code from an article in this month’s Dr Dobb’s. It requires using virtual inheritance to provide an abstraction to templated classes. My problem is that VS2k5, doesn’t like virtual inheritance from empty classes, or classes with no virtual functions. Is this proper behavior for the compiler? edit: The error I get is: error C2683: 'dynamic_cast' : 'A' is not a polymorphic type
class A
{};

class B : public virtual A
{
public:
void output()
{
std::cout << "test" << std::endl;
}
};

int main()
{

A* a = new B;
B* b = dynamic_cast< B* > (a);
b->output();

system( "pause" );
return 0;
}



##### Share on other sites
A type is polymorphic if and only if it has a virtual function. Virtual inheritance have very little to do with that. Additionally, most uses of polymorphic object also require a virtual destructor.

This is perfectly correct behavior, yes. dynamic_cast relies on run-time type information that is typically only generated (and logically so) for polymorphic types.

##### Share on other sites
Quote:
 Original post by FrunyA type is polymorphic if and only if it has a virtual function. Virtual inheritance have very little to do with that. Additionally, most uses of polymorphic object also require a virtual destructor.This is perfectly correct behavior, yes. dynamic_cast relies on run-time type information that is typically only generated (and logically so) for polymorphic types.

Thanks for the quick response. So virtual inheritance's only purpose is to prevent a derived class from inheriting the same base class more than once? Is there no way to create an empty base class that is polymorphic?

##### Share on other sites
Quote:
 Original post by SutekhThanks for the quick response. So virtual inheritance's only purpose is to prevent a derived class from inheriting the same base class more than once? Is there no way to create an empty base class that is polymorphic?

Yeah, that's basically the long and the short of what virtual inheritance is for. As for a polymorphic base class, you could make a class with only an empty virtual destructor. If you get lucky your compiler might even optimize it away.

class base_class{    virtual ~base_class() {}};

Since you're likely to be trying to delete derived classes from pointers to the base in the sort of scheme you're using anyway, you'll have to give your base a virtual destructor either way to make sure it works right. Remember, in the following example, derived_class' destructor will NOT be called properly.

class base_class {};class derived_class : public base_class{    ~derived_class()    {        ... do some stuff here ...    }};...base_class *obj = new derived_class;delete obj;

Hence the need for virtual destructors.

• 16
• 9
• 13
• 41
• 15