Is is safe to instantiate a class inside a member function of that class? For example, let’s say I have class CMyClass with member function CMyClass::MemberFunc, and I want to create another instance of CMyClass inside of CMyClass::MemberFunc.
void CMyClass::MemberFunc( void )
{
CMyClass * pMyClass = new CMyClass();
}
Is this legal/safe? I know it compiles. What I am concerned about is recursion. Will I run into a recursion error when I instantiate CMyClass the first time from the main application?
void main( void )
{
static CMyClass * s_pMyClass = new CMyClass(); // Will this cause recursion?
}
Or, will recursion only occur only if the specific member function with the additional class instance is called?
void CMyClass::MemberFunc( void )
{
CMyClass * pMyClass = new CMyClass();
pMyClass->MemberFunc(); // Pretty sure this will cause a recursive loop.
}
In other words, can I safely instantiate a given class within a member function of that class, so long as I do not call that member function of the second instance of that class? Thanks.
This isn’t more or less safe than instantiating any other object. Note that in your example at the bottom, the recursion is strictly based on the fact that the method calls itself; it would recurse indefinitely regardless.
In sum: you should be fine.