returning an abstract class from a function

后端 未结 7 802
甜味超标
甜味超标 2020-12-03 07:07

Is it possible to return an abstract class(class itself or a reference, doesn\'t matter) from a function?

7条回答
  •  生来不讨喜
    2020-12-03 07:32

    I know I'm little late but I hope this will help someone...

    Being a newbie in C++ programming, I've also been stuck for a while on that problem. I wanted to create a factory method that returns an reference to an abstract object. My first solution using pointers worked well but I wanted to stay in a more "C++ manner". Here is the code snippet I wrote to demonstrate it:

    #include 
    
    using std::cout;
    using std::endl;
    
    class Abstract{
    public:
      virtual void foo() = 0;
    };
    
    class FirstFoo: public Abstract{
      void foo()
      {
        cout << "Let's go to the foo bar!" << endl;
      }
    };
    
    class SecondFoo: public Abstract{
      void foo()
      {
        cout << "I prefer the foo beer !" << endl;
      }
    };
    
    Abstract& factoryMethod(){
      static int what = 0;
    
      if(what++ % 2 == 0)
        return *(new FirstFoo());
      else
        return *(new SecondFoo());
    }
    
    int main(int argc, char* argv[])
    {
      int howMany = 10;
      int i = 0;
    
      while(i++ < howMany)
      {
        Abstract& abs = factoryMethod();
        abs.foo();
        delete &abs;
      }
    }
    

    Open to any critism !

提交回复
热议问题