Can multiple base classes have the same virtual method?

与世无争的帅哥 提交于 2021-02-10 18:50:53

问题


  1. class A has a pure virtual method read()
  2. class B has an implemented virtual method read()
  3. I have a class C that inherits A and B
  4. Can this happen?

What I'm trying to achieve is that the two base classes A and B complement each other.

So C read() method would actually call class B read()

class A {
    virtual int get_data() = 0;

    void print() {
        log(get_data());
    }
}

class B {
    virtual int get_data() {
        return 4;
    }
}

class C : public A, public B {

}
C my_class;
my_class.print(); // should log 4;

I'm not on my computer nor will have opportunity in the next couple of weeks so I can't test this... but I'm designing the architecture and needed to know if this is possible and if not.. how can this be accomplished!


回答1:


Can multiple base classes have the same virtual method?

  1. Can this happen?

Yes.

So C read() method would actually call class B read()

That doesn't happen automatically. A member function of base doesn't override a function of an unrelated base.

You can add an override to C:

class C : public A, public B {
    int get_data() override;
}

This overrides both A::get_data and B::get_data. In order to "actually call class B read()", you can indeed make such call:

int C::get_data() {
    return B::get_data();
}

Or... that would be possible if you hadn't declared B::get_data private.


Overriding a function in another base without explicitly delegating in derived is possible if you change your hierarchy a bit. In particular, you need a common base, and virtual inheritance:

struct Base {
    virtual int get_data() = 0;
};

struct A : virtual Base {
    void print() {
        std::cout << get_data();
    }
};

struct B : virtual Base {
    int get_data() override {
        return 4;
    }
};

struct C : A, B {};


来源:https://stackoverflow.com/questions/55445840/can-multiple-base-classes-have-the-same-virtual-method

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