My class has a static creator function that will instantiate and initialize
an object. The initialization requires access to private members. Is there
a way to define a class' own static member function as a friend to that class?

class CMyClass
{
public:
static CMyClass *Create(int someValInit);

private:
int m_SomeVal;

};

CMyClass *CMyClass::Create(int someValInit)
{
// simplified sample
// my implementation using ATL CComObjectRootEx,
// and object creation is via CComObject::CreateInstance
// which can only use default ctor

CMyClass *pRet = new CMyClass;

pRet->m-SomeVal = someValInit;

return pRet;
}

Re: Can a class' static member func be a friend of that class? by Victor

Victor
Tue Feb 07 14:20:33 CST 2006

jonathannah wrote:
> My class has a static creator function that will instantiate and initialize
> an object. The initialization requires access to private members. Is there
> a way to define a class' own static member function as a friend to that class?

Why? Any member of a class has all access to all of its members without
exceptions.

> class CMyClass
> {
> public:
> static CMyClass *Create(int someValInit);
>
> private:
> int m_SomeVal;
>
> };
>
> CMyClass *CMyClass::Create(int someValInit)
> {
> // simplified sample
> // my implementation using ATL CComObjectRootEx,
> // and object creation is via CComObject::CreateInstance
> // which can only use default ctor
>
> CMyClass *pRet = new CMyClass;
>
> pRet->m-SomeVal = someValInit;

Yes, this is allowed. However, instead of assigning, why don't you use
a private constructor, for example? That's actually more efficient. You
would need to write

return new CMyClass(someValInit);

and that's all. One-liner can't be beat.

>
> return pRet;
> }

V
--
Please remove capital As from my address when replying by mail
Sorry, I do not respond to top-posted replies, please don't ask

RE: Can a class' static member func be a friend of that class? by jonathannah

jonathannah
Tue Feb 07 14:25:30 CST 2006

Never mind, it was a problem specific to CComObject, .



"jonathannah" wrote:

> My class has a static creator function that will instantiate and initialize
> an object. The initialization requires access to private members. Is there
> a way to define a class' own static member function as a friend to that class?
>
> class CMyClass
> {
> public:
> static CMyClass *Create(int someValInit);
>
> private:
> int m_SomeVal;
>
> };
>
> CMyClass *CMyClass::Create(int someValInit)
> {
> // simplified sample
> // my implementation using ATL CComObjectRootEx,
> // and object creation is via CComObject::CreateInstance
> // which can only use default ctor
>
> CMyClass *pRet = new CMyClass;
>
> pRet->m-SomeVal = someValInit;
>
> return pRet;
> }

Re: Can a class' static member func be a friend of that class? by Alex

Alex
Wed Feb 08 02:51:18 CST 2006

If you need singletone COM object, then just include
DECLARE_CLASSFACTORY_SINGLETON macro in your object's class
definition.