0% found this document useful (0 votes)
18 views7 pages

Virtual Inheritance1.1

Uploaded by

shariqqayyum612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

Virtual Inheritance1.1

Uploaded by

shariqqayyum612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Diamond Problem

• The Diamond Problem is an ambiguity error that arises in multiple


inheritance when a derived class inherits from two or more base
classes that share a common ancestor. This results in the inheritance
hierarchy forming a diamond shape, hence the name "Diamond
Problem." The ambiguity arises because the derived class has multiple
paths to access members or methods inherited from the common
ancestor, leading to confusion during method resolution and member
access.
Diamond Problem
Issues in the diamond Problem
• Without special handling, D inherits two separate copies of A, which
causes:
• Ambiguity:
– If A has a member function or variable, the compiler cannot determine which
version of A to use when accessed from D.
• Redundancy:
– Two separate instances of A exist within D, which can lead to increased
memory usage and inconsistent states.
D obj;
obj.someFunction();
Multiple Inheritance(Example)
//simple example showing multiple inheritance
class base1 {
public:
void funbase1(void) { cout<<"funbase1"; }
};

class base2 {
public:
void funbase2(void) { cout<<"funbase2"; }
};

class derived:public base1, public base2 {


public:
void funderived(void) { cout<<"funderived";}
};

void main(void) {
derived der;
der.funbase1();
der.funbase2();
der.funderived();
}
Multiple Inheritance Example (ambiguity)

class A { public: void Foo() {} } A A


class B : public A {}
class C : public A {}
class D : public B, public C {}
B C

D d; D

d.Foo();

is this B's Foo() or C's Foo() ??


Virtual Inheritance
• Virtual inheritance is a feature in C++ that addresses problems related
to multiple inheritance, specifically the diamond problem. It ensures
that when a base class is inherited through multiple paths, there is
only one shared instance of the base class in the derived class,
preventing redundancy and ambiguity.
Solution (virtual inheritance)
class A {
public: void Foo() {} A
}

class B : virtual public A {


} B C

class C : public virtual A {


}
D
class D : public B, public C {
}

D d;
d.Foo(); // no longer ambiguous

You might also like