Have I created a proper factory function?

Hi
I was hoping someone could tell me if the create function I use in quiz.cpp between lines 27-37 is a factory function? I have googled for what a factory function is and am still a little confused but I think this is correct and just need validation please.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//Quiz.h
#ifndef QUIZ_HPP
#define QUIZ_HPP
#include <iostream>
#include <memory>
using namespace std;

enum QUIZ_TYPE {SPORTS, MUSIC};

class Quiz
{
public:
      Quiz(){};
      virtual ~Quiz(){};

      virtual void AskQuestion() = 0;
      static tr1::shared_ptr<Quiz> Create(QUIZ_TYPE choice);
};

#endif

//Quiz.cpp
#include "Quiz.h"
#include "SportsQuiz.h"
#include "MusicQuiz.h"

tr1::shared_ptr<Quiz> Quiz::Create(QUIZ_TYPE choice)
{
      switch(choice)
      {
       case(SPORTS):
            return tr1::shared_ptr<Quiz>(new SportsQuiz);
       case(MUSIC):
            return tr1::shared_ptr<Quiz>(new MusicQuiz);
       // leaving out a default value for now
       }
}


//SportsQuiz.h
#ifndef SPORTSQUIZ_HPP
#define SPORTSQUIZ_HPP

#include "Quiz.h"

class SportsQuiz: public Quiz
{
public:
       SportsQuiz(){cout<<"Sports Constructor\n";}
       ~SportsQuiz(){cout<<"Sports Destructor\n";}

       void AskQuestion(){cout<<"Ask Sports Question\n";}
};

#endif       

//I have a .h file called MusicQuiz that does pretty much the same as SportsQuiz only replaces the word Sports with Music

//Main.cpp
#include "Quiz.h"
#include "SportsQuiz.h"
#include "MusicQuiz.h"

int main()
{
      int choice = 0;

      while(true)
      {
         cout<<"Please Select the type of Quiz to take\n";
         cout<<"(0)SportsQuiz (1)MusicQuiz (2) Quit: ";
         cin>>choice;

         if(choice == 2) break;
     
         tr1::shared_ptr<Quiz>spq(Quiz::Create(static_cast<QUIZ_TYPE>(choice)));

         spq->AskQuestion();
      }
      
      return 0;
}


This code works and outputs the correct text of Ask Sports Question or music depending on what the user selects but is it a factory function or have I got the wrong end of the stick altogether?

Thanks
It sure looks like a factory to me.
Thanks webJose
Topic archived. No new replies allowed.