Among object-oriented languages, one feature that varies considerably is whether the language allows multiple inheritance. C++ does but Ada does not. Java takes a middle ground approach of allowing multiple inheritance of interfaces but not classes. Using a C++ example, illustrate some of the complexities that multiple inheritance introduces. How does C++ deal with them? Why does Java's middle ground approach offer some of the benefits of multiple inheritance while avoids its problems.
The problem with multiple inheritance occur during function overriding. Example:
class A {
public:
void func( ) {}
};
class B {
void func( ) {}
};
class Derived : public A, public B {};
int main() {
Derived d;
d.func()
}
In the above example, both class A and B have similar function func(), therefore the compiler will produce an error since it does not know which function to call.
This problem can be solved using the scope resolution function to specify which function to class eitherย A or B.
int main() {
d.A::func( ); // calls the class A function
d.B::func(); // calls the class B function
}
Comments
Leave a comment