Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiple inheritance preventing diamond

Is there a way to define a class Foo in C++ so that

  1. I can inherit from it
  2. I can't "diamond inherit" from it

I.e.

class Cat: public Foo{} // okay
class Dog: public Foo{} // okay
class Weird: public Cat, public Dog {} // I want this to throw a compiler error
like image 283
anon Avatar asked Feb 23 '10 05:02

anon


People also ask

Does multilevel inheritance cause Diamond problems?

Hence, at any given level in the inheritance chain, there can be at most one implementation of any method. Thus, single-inheritance method implementation does not exhibit the Diamond Problem even with multiple-inheritance of interfaces.

How can you avoid inheriting diamonds?

The solution to the diamond problem is to use the virtual keyword. We make the two parent classes (who inherit from the same grandparent class) into virtual classes in order to avoid two copies of the grandparent class in the child class.

Which type of inheritance leads to diamond problem multi level multiple?

Which type of inheritance results in the diamond problem? Explanation: In diamond problem, hierarchical inheritance is used first, where two different classes inherit the same class and then in turn a 4th class inherits the two classes which had inherited the first class.

What is a diamond problem in multiple inheritance and how we can solve it?

Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call. This issue is known as diamond problem in Java. Due to this Java does not support multiple inheritance i.e., you cannot extend more than one other class.


2 Answers

Cprogramming.com Tutorial: Solving the Diamond Problem in C++ with ...

http://www.cprogramming.com/tutorial/virtual_inheritance.html

Try This

For this type problem can be Avoid or solve by interface.

like image 113
ratty Avatar answered Nov 16 '22 02:11

ratty


Another source of information:

http://www.parashift.com/c++-faq-lite/multiple-inheritance.html

Actually the whole C++ faq little it is really worth reading if you are programming on C++.

like image 35
javier-sanz Avatar answered Nov 16 '22 03:11

javier-sanz