Hi All,
In below code i am surprised to see destructor for rectangle class is not being called though base class destructor for IShape is virtual.
below is the output of below programme:
draw the rectangle
draw the circle draw destructor
deleting circle
deleting the Rectangle is missing from output though constructor for Rectangle is called.
Is there any design flaw with this code ?
Note: in below code destruction of base class pointer is done through destructor of draw class.
#include<iostream>
#include <memory>
using namespace std;
typedef enum result
{
result_error = 0,
result_success = 1
} RESULT_T;
class IShape
{
public:
static IShape* create_instance(string param);
RESULT_T draw ()
{
return Do_Draw();
}
virtual ~ IShape(){}
private:
RESULT_T virtual Do_Draw( )=0;
};
class Circle : public IShape
{
int* p;
public:
Circle()
{
p =new int (12);
}
RESULT_T Do_Draw()
{
cout<<"draw the circle ";
return result_success ;
}
~ Circle(){
delete p;
cout<<"deleting circle"<<endl;
}
};
class Rectangle : public IShape
{
int *p;
public:
Rectangle()
{
p=new int (10);
}
RESULT_T Do_Draw()
{
cout<<"draw the rectangle "<<endl;
return result_success ;
}
~Rectangle(){
delete p;
cout<<"deleting the Rectangle"<<endl;
}
};
IShape* IShape::create_instance(string param)
{
if(param=="Circle")
{
return new Circle;
}
else if (param=="Rectangle")
{
return new Rectangle;
}
return NULL;
}
class Draw
{
IShape *obj;
public:
void Set_draw(string param)
{
obj=(IShape::create_instance(param ));
}
void Draw_Shape()
{
obj->draw();
}
~Draw( ){ cout<<"draw destructor"<<endl;delete obj;} // it is not responsible for deletion of IShape object.
};
int main()
{
RESULT_T final_ret_code=result_error;
Draw obj;
obj.Set_draw ("Rectangle");
obj.Draw_Shape();
obj.Set_draw ("Circle");
obj.Draw_Shape();
return 1;
}