Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Virtual base class


Published on

Published in: Education, Technology
  • Login to see the comments

Virtual base class

  2. 2. DIAMOND PROBLEM Base Class Derived 1 Derived 2 Derived 3
  3. 3. EXAMPLEclass one{ public: int a; public: one() { cout<<"onen"; }};class two : public one{ public: int a2; public: two(){ cout<<"twon"; }};
  4. 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. 5. int main(){ four f;return 0;}OUTPUT:One Two copies copies of one presentTwo in an object of type four.OneThreeFour
  6. 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. 7. HOW TO RESOLVETwo ways: Manual Selection. Using virtual base class.
  8. 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. 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. 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. 11. int main(){ four f; return 0;}OUTPUT:ONE Only one copy is maintained.TWO No ambiguity.THREEFOUR
  12. 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.
  13. 13. THANK YOU