SlideShare a Scribd company logo
1 of 13
VIRTUAL BASE CLASS
DIAMOND PROBLEM

                 Base Class




     Derived 1                 Derived 2




                   Derived 3
EXAMPLE
class one
{
    public:
         int a;
     public:
              one() { cout<<"onen"; }
};


class two : public one
{
    public:
         int a2;
    public:
              two(){ cout<<"twon"; }
};
class three : public one
{
    public:
         int a3;
     public:
              three(){ cout<<"threen"; }
};

class four: public two , public three
{
    private:
         int a4;
     public:
              four(){ a4=6;cout<<"fourn"; }
};
int main()
{
    four f;
return 0;
}

OUTPUT:
One
              Two copies copies of one present
Two           in an object of type four.
One
Three
Four
int main()
{
  four f;
  cout<<f.a; //error : request for member ‘a’ is ambiguous
  return 0;
}

   Ambiguous because variable „a‟ is present twice in the object
    of four, one in two class and one in three class.


   Because there are two copies of „a‟ present in object „f‟, the
    compiler doesn‟t not know which one is being referred.
HOW TO RESOLVE


Two ways:

   Manual Selection.

   Using virtual base class.
MANUAL SELECTION
   Manually select the required variable ‘a’ by the using
    scope resolution operator.

    int main()
    {
        four f;

       f.two::a=40;                       OUTPUT:

       f.three::a=50;                     40
                                          50
       cout<<f.two::a<<“n”;
       cout<<f.three::a<<“n”;

    return 0;
    }
   f.two::a=40; and f.three::a=50;

   In the above statements, use of scope resolution operators
    resolves the problem of ambiguity.

   But this is not an efficient way because still two copies of
    „a‟ is available in object „f‟.

   How to make only one copy of „a‟ available in the object
    „f‟ which consumes less memory and easy to access without
    using scope resolution operator.

   This can be done by using virtual base class.
VIRTUAL BASE CLASS
 class one                          class two : virtual public one
 {                                  {
     public:                            public:
          int a;                             int a2;
      public:                           public:
      one() {cout<<"onen"; }               two(){ cout<<"twon"; }
 };                                 };


class three:virtual public one      class four: public two , public three
{                                   {
    public:                             private:
         int a3;                             int a4;
     public:                             public:
       three(){cout<<"threen"; }              four(){ a4=6;cout<<"fourn"; }
};                                  };
int main()
{
    four f;
    return 0;
}


OUTPUT:
ONE             Only one copy is maintained.
TWO             No ambiguity.
THREE
FOUR
int main()
{
    four f;
    f.a=40; //    umambigious since only one copy of ‘a’ is present in
                  object ‘f’
    cout<<f.a;
     return 0;
}


   Now that both two and three have inherited base as virtual, any
    multiple inheritance involving them will cause only one copy of base to
    be present.

   Therefore, in FOUR, there is only one copy of base.
THANK YOU

More Related Content

What's hot

Friend function
Friend functionFriend function
Friend functionzindadili
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arraysNeeru Mittal
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++Sujan Mia
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Kamlesh Makvana
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 

What's hot (20)

Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Friend function
Friend functionFriend function
Friend function
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Inline function
Inline functionInline function
Inline function
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
class and objects
class and objectsclass and objects
class and objects
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 

Viewers also liked

Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Permutation & Combination
Permutation & CombinationPermutation & Combination
Permutation & CombinationPuru Agrawal
 
Permutations and combinations examples
Permutations and combinations examplesPermutations and combinations examples
Permutations and combinations examplesLeo Crisologo
 
Permutation and combination
Permutation and combinationPermutation and combination
Permutation and combinationSadia Zareen
 
Permutations & Combinations
Permutations & CombinationsPermutations & Combinations
Permutations & Combinationsrfant
 

Viewers also liked (9)

Stack
StackStack
Stack
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
16 combinatroics-2
16 combinatroics-216 combinatroics-2
16 combinatroics-2
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Permutation & Combination
Permutation & CombinationPermutation & Combination
Permutation & Combination
 
Permutations and combinations examples
Permutations and combinations examplesPermutations and combinations examples
Permutations and combinations examples
 
Permutation and combination
Permutation and combinationPermutation and combination
Permutation and combination
 
Permutations & Combinations
Permutations & CombinationsPermutations & Combinations
Permutations & Combinations
 

Similar to Virtual base class

Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsPrincess Sam
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdfstudy material
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-iiDeepak Singh
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Abu Saleh
 
MODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerMODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerssuser6f3c8a
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple InheritanceBhavyaJain137
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
Unit3 java
Unit3 javaUnit3 java
Unit3 javamrecedu
 
Polymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformaticsPolymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformaticsPriyanshuMittal31
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphismFALLEE31188
 

Similar to Virtual base class (20)

Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-ii
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
 
MODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerMODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computer
 
inhertance c++
inhertance c++inhertance c++
inhertance c++
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
Lab3
Lab3Lab3
Lab3
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture4
Lecture4Lecture4
Lecture4
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
 
Polymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformaticsPolymorphism and Virtual Functions ppt bioinformatics
Polymorphism and Virtual Functions ppt bioinformatics
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 

More from Tech_MX

Theory of estimation
Theory of estimationTheory of estimation
Theory of estimationTech_MX
 
String & its application
String & its applicationString & its application
String & its applicationTech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating SystemTech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pcTech_MX
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbmsTech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbmsTech_MX
 
Linear regression
Linear regressionLinear regression
Linear regressionTech_MX
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interruptTech_MX
 
Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loadersTech_MX
 

More from Tech_MX (20)

Uid
UidUid
Uid
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Spss
SpssSpss
Spss
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Set data structure
Set data structure Set data structure
Set data structure
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
More on Lex
More on LexMore on Lex
More on Lex
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 
Linkers
LinkersLinkers
Linkers
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
 
Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
 

Recently uploaded

CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptxAneriPatwari
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 

Recently uploaded (20)

CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptx
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 

Virtual base class

  • 2. DIAMOND PROBLEM Base Class Derived 1 Derived 2 Derived 3
  • 3. EXAMPLE class one { public: int a; public: one() { cout<<"onen"; } }; class two : public one { public: int a2; public: two(){ cout<<"twon"; } };
  • 4. class three : public one { public: int a3; public: three(){ cout<<"threen"; } }; class four: public two , public three { private: int a4; public: four(){ a4=6;cout<<"fourn"; } };
  • 5. int main() { four f; return 0; } OUTPUT: One Two copies copies of one present Two in an object of type four. One Three Four
  • 6. int main() { four f; cout<<f.a; //error : request for member ‘a’ is ambiguous return 0; }  Ambiguous because variable „a‟ is present twice in the object of four, one in two class and one in three class.  Because there are two copies of „a‟ present in object „f‟, the compiler doesn‟t not know which one is being referred.
  • 7. HOW TO RESOLVE Two ways:  Manual Selection.  Using virtual base class.
  • 8. MANUAL SELECTION  Manually select the required variable ‘a’ by the using scope resolution operator. int main() { four f; f.two::a=40; OUTPUT: f.three::a=50; 40 50 cout<<f.two::a<<“n”; cout<<f.three::a<<“n”; return 0; }
  • 9. f.two::a=40; and f.three::a=50;  In the above statements, use of scope resolution operators resolves the problem of ambiguity.  But this is not an efficient way because still two copies of „a‟ is available in object „f‟.  How to make only one copy of „a‟ available in the object „f‟ which consumes less memory and easy to access without using scope resolution operator.  This can be done by using virtual base class.
  • 10. VIRTUAL BASE CLASS class one class two : virtual public one { { public: public: int a; int a2; public: public: one() {cout<<"onen"; } two(){ cout<<"twon"; } }; }; class three:virtual public one class four: public two , public three { { public: private: int a3; int a4; public: public: three(){cout<<"threen"; } four(){ a4=6;cout<<"fourn"; } }; };
  • 11. int main() { four f; return 0; } OUTPUT: ONE Only one copy is maintained. TWO No ambiguity. THREE FOUR
  • 12. int main() { four f; f.a=40; // umambigious since only one copy of ‘a’ is present in object ‘f’ cout<<f.a; return 0; }  Now that both two and three have inherited base as virtual, any multiple inheritance involving them will cause only one copy of base to be present.  Therefore, in FOUR, there is only one copy of base.