chacham15
chacham15

Reputation: 14281

Can an inherited class override another inherited class' virtual function?

Is the following legal?

class Base {
    virtual void foo() = 0;
};

class Fooable {
    void foo(){}
};

class Child : public Base, public Fooable {

};

What happens if a class inherits from two classes which both have foo()? What if Base::foo() werent abstract?

Upvotes: 0

Views: 67

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126488

Since Base and Fooable don't have a comment virtual base, when you inherit from both of them, you get two independent foo functions that don't interact despite having the same name.

You can do what you want by using common virtual base classes:

class Base {
    virtual void foo() = 0;
};

class Fooable : public virtual Base {
    void foo(){}
};

class Child : public virtual Base, public virtual Fooable {

};

Though if you want to be able to call foo, you'll need to make it public rather than private.

Upvotes: 0

carl_h
carl_h

Reputation: 2183

Since foo is virtual in Base, if you don't implement foo() in Child then compilation fails if you try to instantiate Child, since Child is still abstract.

If Base::foo() were not abstract, you'd need to specify which foo you were calling as follows: Child *child = new Child; child->Base::foo(); child->Fooable::foo()

Upvotes: 2

Related Questions