I have this class:

class Pizza{
protected:
 string desc;
public: 
 Pizza(){
  desc = "unknown pizza";
 }
 virtual string getdesc(){
  return desc;
 }
 virtual double cost(){
  return 0;
 }
};

And one of its subclass:

class Small: public Pizza{
public:
 Small(){
  desc = "Small";
 }
 double cost(){
  return 8.00;
 }
};

Besides the "Small" class there are others that are similar, eg. "Medium", "Large", etc.

I want to implement a Factory class for this. However, it doesnt seem to work:

class PizzaFactory: public Pizza{
public:
 Pizza* getPizzaInstance( int id );
};
 
Pizza* PizzaFactory::getPizzaInstance( int id ) {
 switch (id) {
 case 1:
  return new Small();
 case 2:
  return new Medium();
  default:
  return NULL;
 }
}

I wonder why when i called in main, it does not give me error but the "id" parameter does not get included into the switch statement.

Any help would be much appreciated.

Recommended Answers

All 4 Replies

There is nothing wrong with your code except " class PizzaFactory: public Pizza{ ". You don't need to derive factory class from base class. Although this would not cause any fatal problems.
Post your main and the some more description of the problem.

There is nothing wrong with your code except " class PizzaFactory: public Pizza{ ". You don't need to derive factory class from base class. Although this would not cause any fatal problems.
Post your main and the some more description of the problem.

The reason i derive factory class from base class is because i want to call the member function of class Pizza directly.

The idea of this is simple. I have class Pizza, its derived classes such as Small, Medium, Large. Now that i want to have a Factory class so that by calling this Factory Class a certain derived class (Small, for instance) will be created, instead of creating new instance by calling directly Small.

Main is as follow:

int main(){
 
 PizzaFactory *p2 = new PizzaFactory;
 p2->getPizzaInstance(1);
 
 cout<<p2->getdesc()<<" $"<<p2->cost()<<endl;
 return 0;
}

It does not give any error but the pizza created is a pizza of type Pizza (generic) and not that of Small, which should have been the one since i call getPizzaINstance(1).

What am i missing?

Thanks

I think i got this one. I'll see if anything else coming up.

So the problem is with main() and not those classes.. Again you shouldn't derive factory from the base.. it's against the pattern..
Change the main() to:

int main(){
    PizzaFactory *p2 = new PizzaFactory;
    Pizza* p = p2->getPizzaInstance(1);

    cout<<p->getdesc()<<" $"<<p->cost()<<endl;
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.