Advertisement
Guest User

Untitled

a guest
Aug 15th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class AbstractBase {
  4.  public:
  5.   virtual ~AbstractBase() = default;
  6.  
  7.   virtual void f() = 0;
  8. };
  9.  
  10. class C1 : public AbstractBase {
  11.  public:
  12.   void f() override {
  13.     std::cout << "From C1" << std::endl;
  14.   }
  15. };
  16.  
  17. class C2 : public AbstractBase {
  18.  public:
  19.   void f() override {
  20.     std::cout << "From C2" << std::endl;
  21.   }
  22. };
  23.  
  24. AbstractBase& CreateC(int i) {
  25.   static auto c1 = C1();
  26.   static auto c2 = C2();
  27.   if (i == 0) {
  28.     return c1;
  29.   } else {
  30.     return c2;
  31.   }
  32. }
  33.  
  34. int main() {
  35.   AbstractBase& c = CreateC(0);
  36.   c.f();
  37.   c = CreateC(1);
  38.   c.f();
  39.   return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement