seesaw said:
class A
{
public:
static A* newA() { return new A; }
...
};
In the code, two things not very clear and natural to me:
1. the method newA() is defined as static.
A static member function is like a free function in that it exists
independently of any individual object of the class. You can call it with
A::newA()
without every having declared an object of type A. By contrast, with a non
static member function called foo, you could NOT call
A::foo()
Instead, you would have to do something like:
A a;
a.foo();
Because a static member function is not bound to an individual class object,
it does not have a "this" pointer that allows it to access member data of an
object.
On the other hand, it is different from a free function in that
1. It belongs to the "namespace" of the class, so that you must call
A::newA() rather than just newA(),
2. It automatically has access rights to an object's private and protected
members in the same way that a free function would have if it was declared a
friend of the class (in both cases, these access rights can only be utilised
if an object of the class is made available to the function in some way,
e.g., by passing a reference to an object as a function argument or by
declaring an object of the class as a local variable within the function).
2. newA as a member method of class A IS returning a "new" instance
of A while it is still defining class A.
newA doesn't return anything just by being defined. It only returns
something when it is called.