Guest User

Untitled

a guest
Feb 21st, 2012
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class X
  6. {
  7. public:
  8.     void x()
  9.     {
  10.         //...
  11.     }
  12. };
  13.  
  14. //for the first attempt
  15. class A1 :public X {};
  16. class B1 :public X {};
  17. class C1 :public A1, public B1 {};
  18.  
  19. //for the second attempt
  20. class A2 :public X {};
  21. class B2 :public X {};
  22. class C2 :public A2, public B2 {};
  23.  
  24. int main(int argc,char *argv[])
  25. {
  26.     //first attempt
  27.     A1 *a1=new A1();
  28.     B1 *b1=new B1();
  29.     C1 *c1=new C1();
  30.  
  31.     a1->x();
  32.     b1->x();
  33.     c1->x();
  34.  
  35.     X *ax1=a1;
  36.     X *bx1=b1;
  37.     X *cx1=c1;
  38.  
  39.     ax1->x();
  40.     bx1->x();
  41.     cx1->x();
  42.  
  43.     a1=(A1 *)ax1;   //Error: cannot convert pointer to base class "X" to pointer to derived class "A1" -- base class is virtual
  44.     b1=(B1 *)bx1;   //Error: cannot convert pointer to base class "X" to pointer to derived class "B1" -- base class is virtual
  45.     c1=(C1 *)cx1;   //Error: cannot convert pointer to base class "X" to pointer to derived class "C1" -- base class is virtual
  46.  
  47.     //second attempt
  48.     A2 *a2=new A2();
  49.     B2 *b2=new B2();
  50.     C2 *c2=new C2();
  51.  
  52.     a2->x();
  53.     b2->x();
  54.     c2->x();    //Error: "C2::x" is ambiguous
  55.  
  56.     X *ax2=a2;
  57.     X *bx2=b2;
  58.     X *cx2=c2;  //Error: base class "X" is ambiguous
  59.  
  60.     ax2->x();
  61.     bx2->x();
  62.     cx2->x();
  63.  
  64.     a2=(A2 *)ax2;
  65.     b2=(B2 *)bx2;
  66.     c2=(C2 *)cx2;   //Error: derived class "C2" contains more than one instance of class "X"
  67.  
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment