Function to create an instance of a class inside a member

Is it possible to instantiate a class inside a member function of this class? For example, let's say I have a class CMyClasswith a member function CMyClass::MemberFunc, and I want to create another instance CMyClassinside CMyClass::MemberFunc.

void CMyClass::MemberFunc( void )
{
    CMyClass * pMyClass = new CMyClass();
}

Is it legal / safe? I know that it compiles. I am worried about recursion. Will I encounter a recursion error when I first create CMyClassfrom the main application?

void main( void )
{
    static CMyClass * s_pMyClass = new CMyClass(); // Will this cause recursion?
}

Or will recursion occur only when a particular member function is called with an additional instance of the class?

void CMyClass::MemberFunc( void )
{
    CMyClass * pMyClass = new CMyClass();
    pMyClass->MemberFunc(); // Pretty sure this will cause a recursive loop.
}

In other words, can I safely create an instance of a given class inside a member function of this class if I don't call this member function of a second instance of this class? Thank.

+5
4

, . , , ; .

: .

+3

(), , .

/?

void CMyClass::MemberFunc( void )
{

    CMyClass * pMyClass = new CMyClass();

    delete pMyClass ;  // newly added.

}

. new delete, , . , .

, - ?

void CMyClass::MemberFunc( void )
{
    CMyClass * pMyClass = new CMyClass();
    pMyClass->MemberFunc(); // Pretty sure this will cause a recursive loop.
}

, , , CMyClass::MemberFunc . ( delete pMyClass; - )

, void , . , C.

+2

, - , . , , - , .

+1

No, this will not cause recursion - your compiler will flag this as an error if this happens. I suspect that you really want to create a static instance of your class (e.g. singleton). Can you post a real use case illustrating what you want to do?

0
source

All Articles