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.
so by line 1, class is both loaded and initialized and hence there is no problem in instantiating an instance of class in itself.
Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier.
In addition to holding data, classes (and structs) can also contain functions! Functions defined inside of a class are called member functions (or sometimes methods). Member functions can be defined inside or outside of the class definition.
A non-member function always appears outside of a class. The member function can appear outside of the class body (for instance, in the implementation file). But, when you do this, the member function must be qualified by the name of its class. This is to identify that that function is a member of a particular class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With