vishwatmasandeep
vishwatmasandeep

Reputation: 25

how to write a factory method; I have errors in following c++ code

I have a Shoe base class. This has a static method Create. This creates 2 derived class objects Shoe8 and Shoe9. The setsize and getsize methods are getter and setter methods for size of Shoe. Here they are 8 and 9 for Shoe8 and Shoe9 respectively. But I get compiler errors. How to get rid of them?

  #include<stdio.h>
    #include<iostream>
    #include<vector>
    using namespace std;

    class Shoe
    {
        int size;
    public:
        static Shoe* Create(int num)
        {
            switch(num)
            {
                case 8:
                      return new Shoe8;
                case 9:
                      return new Shoe9;
            }
        }

        virtual void Detail() = 0;
        int getsize()
        {   
            return size;
        }
        void setsize(int sz)
        {   
            size = sz;
        }
    };


    class Shoe8:Shoe
    {
    public:
        Shoe8()
        {   
            setsize(8);
        }

        void Detail()
        {   
            cout<<"size = "<<getsize()<<endl;
        }
    };

    class Shoe9:Shoe
    {
    public:
        Shoe9()
        {   
            setsize(9);
        }

        void Detail()
        {   
            cout<<"size = "<<getsize()<<endl;
        }
    };

error I get is

factory.cpp: In static member function ‘static Shoe* Shoe::Create(int)’:
factory.cpp:15:30: error: ‘Shoe8’ does not name a type; did you mean ‘Shoe’?
                   return new Shoe8;
                              ^~~~~
                              Shoe
factory.cpp:17:30: error: ‘Shoe9’ does not name a type; did you mean ‘Shoe’?
                   return new Shoe9;
                              ^~~~~

Then I tried with forward declarations

class Shoe8;
class Shoe9;

I get following errors

factory.cpp: In static member function ‘static Shoe* Shoe::Create(int)’:
factory.cpp:19:30: error: invalid use of incomplete type ‘class Shoe8’
                   return new Shoe8;
                              ^~~~~
factory.cpp:7:7: note: forward declaration of ‘class Shoe8’
 class Shoe8;
       ^~~~~
factory.cpp:21:30: error: invalid use of incomplete type ‘class Shoe9’
                   return new Shoe9;
                              ^~~~~
factory.cpp:8:7: note: forward declaration of ‘class Shoe9’
 class Shoe9;

Upvotes: 1

Views: 126

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 39086

Just separate method declarations and definitions, so when you define/implement the method Create, all class definitions are already available.

class Shoe
{
    int size;
  public:
    static Shoe* Create(int num);
    // Rest part of class
};

// Other classes go here

// After all classes are defined
Shoe* Shoe::Create(int num)
{
    switch(num)
    {
        case 8:
              return new Shoe8;
        case 9:
              return new Shoe9;
    }
}

Upvotes: 2

Related Questions