How to set data members of derived product class in factory design pattern?
class Factory
{
public:
product* Create(int type)
{
switch (type)
{
case 1:
return new product1;
break;
case 2:
return new product2;
break;
}
}
};
class product
{
int a;
public :
product();
product(int a);
void seta (int a);
};
class product1:public product
{
int b;
public:
product1();
product1(int a,int b):product(a), b(b) {}
void setb (int b);
};
class product2:public product
{
int c;
public:
product2();
product2(int a, int c):product(a), c(c) {}
void setc (int c);
};
\\ client code
void main()
{
Factory f;
product* p = f.create(1); // product1 created
p->seta(2);
// now how to set value b of product1
}
Note: if I down cast the p to p1 then there will be no point of using factory. Hence don't know how to use it.
EDIT : set method added for product, product1, product2. How to set value for b in main if product1 created using factory?
productcould have some (pure) virtual methods. The effect of calling such methods depends on the dynamic type of the object, no downcast is necessary.