+ 3

C++ supports multiple inheritance. What is the 'diamond problem' that can occur with multiple inheritance? Give an example.

9th Aug 2020, 4:55 PM
shree kapoor
shree kapoor - avatar
6 Respostas
+ 1
Not need example it is very easy problem. You have class A, then you habe class B and C inherit from A and classD inherit from B and C. In this case diagram will be diamong(name of problem) in all classes you have some virtual function f() So when you create instance of class D and call finction f, the compiler do not know which of way construct d:f-c:f-a:f or d:f-b:f-a:f.(imagine that compiler need construct way). So for this need use virtual inheritence, and in this case it will be use first declarated parent class name
9th Aug 2020, 7:05 PM
george
george - avatar
+ 5
the problems that arises due to multiple inheritance is the diamond problem. A classical illustration of this is given by Bjarne Stroustrup (the creator of C++) in the following example: class storable class inherited by transmitter and receiver classes { public: storable(const char*); virtual void read(); virtual void write(); virtual ~storable(); private:} class transmitter: public storable { public: void write();} class receiver: public storable { public: void read(); } class radio: public transmitter, public receiver { public: void read(); } Since both transmitter and receiver classes are using the method write() from the base class, when calling the method write() from a radio object the call is ambiguous; the compiler can't know which implementation of write() to use, the one from the transmitter class or the one from the receiver class https://www.cprogramming.com/tutorial/virtual_inheritance.html
11th Aug 2020, 7:26 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 2
Diamond problem solve occured when Two base classes of a class have common superclass A /. \. D will get common member of B. C. B,C twice which are of A \. /. And produce a ambiguous D. Situation
10th Aug 2020, 7:41 AM
Rohit Kadayan
Rohit Kadayan - avatar