Inherit from two polymorphic classes

孤人 提交于 2019-12-12 19:18:36

问题


Given the following code

class T {
    public:
        virtual ~T () {}
        virtual void foo () = 0;
};

class U {
    public:
        U() {}
        ~U() {}
        void bar () { std::cout << "bar" << std::endl; }
};

class A : public U, public T {
    public:
        void foo () { std::cout << "foo" << std::endl; }
};

int main () {
    A * a = new A;

    std::vector<U*> u;
    std::vector<T*> t;

    u.push_back(a);

    t.push_back(reinterpret_cast<T*>(u[0]));

    u[0]->bar ();
    t[0]->foo ();

    delete a;
    return 0;
}

I get the output I would expect

bar
foo

However, if I change the definition of U to

class U {
    public:
        U() {}
        virtual ~U() {}
        virtual void bar () { std::cout << "bar" << std::endl; }
};

I still compile fine and without warnings/errors but the output is now

bar
bar

What is it about the virtual declaration that prevents me from calling into the foo?


回答1:


Firstly, there are no virtual base classes in your example. Classes that contain virtual functions are called polymorphic. (There is such thing as "virtual base classes" in C++ but it has nothing to do with your example.)

Secondly, the behavior of your code does not depend on any virtual declarations. You have deliberately destroyed the integrity of the base pointer by using reinterpret_cast. For this reason the behavior of the code is undefined.

A direct cast from one base pointer to another (which is what you are trying to do in your code) is called cross-cast. The only cast in C++ that can carry out a cross-cast is dynamic_cast.

t.push_back(dynamic_cast<T *>(u[0])); 

You can perform an indirect cross-cast without dynamic_cast, but for that you have to downcast the pointer to the derived type first (A *) using static_cast and then upconvert it to another base pointer type

t.push_back(static_cast<A *>(u[0])); // upconversion to `T *` is implicit



回答2:


If you use reinterpret_cast you loose all guarantees, and anything you do is "undefined behaviour". In this case, I expect the VMT got messed up, or the VPTR overwritten.

As an illustration, when I compile the first code above, I get a segfault on execution on my compiler.

If you really want to "cross-execute" you should derive from a common base class, and inherit that base class by U and T virtually ( : virtual public), or use dynamic_cast instead of reinterpret_cast.




回答3:


Populate t just like you did u:

t.push_back(a);

You don't need reinterpret_cast because A is a T.



来源:https://stackoverflow.com/questions/2158928/inherit-from-two-polymorphic-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!