Guest User

Untitled

a guest
Sep 30th, 2014
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5.  
  6. class A
  7. {
  8.       protected:
  9.              virtual int Add() { cout << "Hello"; }
  10.              
  11.       public:
  12.              void Dec() { cout << "\n"; }
  13.              
  14.       private:
  15.               int a;
  16. };
  17.  
  18.  
  19. class B : public A
  20. {
  21.       public:
  22.              virtual int Add(int a) { A::Add(); cout << " World"; }
  23. };
  24.  
  25. class C : public A
  26. {
  27.       public:
  28.              virtual int Add() { cout << "!"; }
  29. };
  30.  
  31.  
  32. // ==================================================
  33. class Factory
  34. {
  35.       public:
  36.              Factory() {}
  37.              
  38.       public:
  39.              A* CreateObject(int a)
  40.              {
  41.                     if (a == 0)
  42.                        return new B();
  43.                     else if (a == 1)
  44.                        return new C();
  45.              }
  46. };
  47. // ==================================================
  48.  
  49.  
  50. int main(void)
  51. {
  52.     Factory f;
  53.     B *b = dynamic_cast<B*>(f.CreateObject(0));
  54.     C *c = dynamic_cast<C*>(f.CreateObject(1));
  55.    
  56.     b->Add(5);
  57.     c->Add();
  58.     b->Dec();
  59.     c->Dec();
  60.     c->Add();
  61.    
  62.     delete c;
  63.     delete b;
  64.    
  65.     // --------------------------------------
  66.     cout << endl << "=====================================" << endl << endl;
  67.    
  68.     B* arrB[3];
  69.     arrB[0] = dynamic_cast<B*>(f.CreateObject(0));
  70.     arrB[1] = dynamic_cast<B*>(f.CreateObject(1)); // <----| ???
  71.     arrB[2] = dynamic_cast<B*>(f.CreateObject(0));
  72.    
  73.     //arrB[1]->Add(4); // error?
  74.    
  75.     delete arrB[0];
  76.     delete arrB[1];
  77.     delete arrB[2];
  78.    
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment