2

I am getting difficult time understand why there is a keyworad "static" in header only (I understand what that code does and how to use it in API

//Header
class A 
{
    static A * create();
    bool init();

};


A* A::create()
{
    A * ob = new (std::nothrow) A();
    if(A && a->init()){
        A->autorealease();
        return A;
    }
    SAFE_DELETE(A);
    return nullptr;
}

Used like this A* testobj = A::create(); (Which will go out of scope if it's not saved in some (vector) array, thus it will be cleaned by the engine).

Thank you.

Dinamix
  • 47
  • 6
  • 1
    I don't understand your question... What are you asking exactly? – Ceros May 12 '17 at 16:59
  • 1
    You only need `static` in the function declaration - it says this function does not require a class instance for it to be called on. –  May 12 '17 at 16:59
  • My apologize if I wrote it wrong. But I am askign the reason of using "Static" pointer instead of just returning pointer. – Dinamix May 12 '17 at 17:00
  • 4
    There is no "static pointer", it's the function that is static. –  May 12 '17 at 17:00
  • @NeilButterworth - Thank you for explanation, now I understand it. – Dinamix May 12 '17 at 17:04
  • You really should pick up a [good book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Captain Obvlious May 12 '17 at 17:10

1 Answers1

5

I am askign the reason of using static pointer instead of just returning pointer

The member function is static, but the pointer it returns is not. The object the function creates is allocated dynamically, and should be deleted in the same way that you delete other objects.

The reason the member function is marked static is to let you run it without creating an instance of the object, i.e.

A* myObj = A::create();

as opposed to

A obj;
A* objPtr = obj.create();

which defeats the purpose of defining a factory function in the first place.

Keyword static is not repeated at the point the member function is defined in accordance with C++ syntax: the compiler already knows from the declaration that A::create is static, so there is no need to repeat this information.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Perhaps it is worth adding that `static` used outside a class definition has a totally different meaning (internal linkage). – themiurge May 12 '17 at 17:15