Please explain memory allocation with instance creation
class simpleTestFactory
{
public:
static simpleTest* Create()
{
return new simpleTest();
}
}
class simpleTest
{
private:
int x,y,z;
public:
int printTest()
{
cout<<"\n This test program";
}
}
int main()
{
simpleTest* s1=simpleTestFactory::Create();
.
.
s1=simpleTestFactory::Create();
}
In the main function we are creating instance for the simpleTest with create static function. Again we are creating another instance for the same object.
In this case the first created instance memory would be deleted??
otherwise how to avoid memory issues??
No, it won’t. You have to deallocate it yourself by calling
delete, or by using a smart pointer in the first place.(I assume that
s1is of typesimpleTest*, i.e. a pointer tosimpleTest, as otherwise your code is not valid C++.)