abstract base classes, multiple inheritence, and common pure virtual methods

半腔热情 提交于 2019-12-20 03:46:09

问题


The following test code seems to indicate that if a class has two abstract base classes with common pure virtual methods, then these methods are "shared" in the derived class.

#include <iostream>
#include <string>

using namespace std;

struct A
{
    virtual string do_a() const = 0;
    virtual void set_foo(int x) = 0;
    virtual int get_foo() const = 0;
    virtual ~A() {}
};

struct B
{
    virtual string do_b() const = 0;
    virtual void set_foo(int x) = 0;
    virtual int get_foo() const = 0;
    virtual ~B() {}
};

struct C : public A, public B
{
    C() : foo(0) {}
    string do_a() const { return "A"; }
    string do_b() const { return "B"; }
    void set_foo(int x) { foo = x; }
    int get_foo() const { return foo; }
    int foo;
};

int main()
{
    C c;
    A& a = c;
    B& b = c;
    c.set_foo(1);
    cout << a.do_a() << a.get_foo() << endl;
    cout << b.do_b() << b.get_foo() << endl;
    cout << c.do_a() << c.do_b() << c.get_foo() << endl;
    a.set_foo(2);
    cout << a.do_a() << a.get_foo() << endl;
    cout << b.do_b() << b.get_foo() << endl;
    cout << c.do_a() << c.do_b() << c.get_foo() << endl;
    b.set_foo(3);
    cout << a.do_a() << a.get_foo() << endl;
    cout << b.do_b() << b.get_foo() << endl;
    cout << c.do_a() << c.do_b() << c.get_foo() << endl;
}

This code compiles cleanly in g++ 4.1.2 (admittedly old), using -std=c++98 -pedantic -Wall -Wextra -Werror. The output is:

A1
B1
AB1
A2
B2
AB2
A3
B3
AB3

This is what I desire, but I question whether this works generally, or only "by accident." Fundamentally, this is my question: can I depend on this behavior, or should I always inherit from a virtual base class for this type of scenario?


回答1:


Don't make it harder than it is. A function with the same signature as a virtual function in a base class overrides the base version. Doesn't matter how many bases you have, or whether another base has a virtual function with the same signature. So, yes, this works.



来源:https://stackoverflow.com/questions/16040411/abstract-base-classes-multiple-inheritence-and-common-pure-virtual-methods

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