Class factory to create derived classes c++

I’m currently learning about class factory patterns with C++. I keep having errors while trying to implement the factory. Suppose I have an abstract class and two derived classes. What I want the factory to do is to create a new object of the base class like so: Ball *sc = new SoccerBall();
I am not sure on how to implement this, I have tried but of no avail. What do I need to fix?

class Ball
{
   public:
   Ball();
   virtual ~Ball();
   virtual int getSize() const = 0;
   virtual void setBallSize(int s) = 0;
   virtual string ballManufacturer() const = 0;
   protected:
   int ballSize;
}
class Soccerball:public Ball
{
   public:
   Soccerball();
   Soccerball(int size);
   ~Soccerball();
   int getSize() const;
   void setBallSize(int s);
   string ballManufacturer() const;
}
class Soccerball:public Ball
{
   public:
   Soccerball();
   Soccerball(int size);
   ~Soccerball();
   int getSize() const;
   void setBallSize(int s);
   string ballManufacturer() const;
}
class Basketball:public Ball
{
   public:
   Basketball();
   Basketball(int size);
   ~Basketball();
   int getSize() const;
   void setBallSize(int s);
   string ballManufacturer() const;
}
class BallFactory
{
   public:
   Ball* createBall(string s)
   {
       if(s == "Soccer")
       {
          return new Soccerball(5);
       }
       if(s == "Basket")
       {
          return new Basketball(6);
       }
   }
}


Source: oop

Leave a Reply