Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Instantiation Inside Member Function

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.

like image 418
Jim Fell Avatar asked May 12 '11 18:05

Jim Fell


People also ask

Can you instantiate a class inside itself?

so by line 1, class is both loaded and initialized and hence there is no problem in instantiating an instance of class in itself.

How do you define member functions inside the class?

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.

Can classes have member functions?

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.

Can we call a non member function inside the class?

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.


1 Answers

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.

like image 108
dlev Avatar answered Sep 27 '22 18:09

dlev