Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Are static member functions ever used?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 noatom   Members   -  Reputation: 785

Like
0Likes
Like

Posted 31 March 2013 - 01:27 PM

Can someone give me an example about when that might come in handy?I can't figure anything! Why would one want a static member function? What problem could you solve just with that?



Sponsor:

#2 Paradigm Shifter   Crossbones+   -  Reputation: 5413

Like
4Likes
Like

Posted 31 March 2013 - 01:32 PM

If you need to pass a regular C-compatible function pointer to something (like a Windows Procedure, or a thread procedure) it has to be static so the calling conventions are the same.

 

Also if you have a member function that doesn't access any members of the class (except static ones) it should be static as well.

 

Class factories use static Create methods which act a bit like constructors as well (they create a new object and return the address).

 

Evil singletons use static methods to get the instance as well...


"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#3 Servant of the Lord   Crossbones+   -  Reputation: 20384

Like
6Likes
Like

Posted 31 March 2013 - 01:33 PM

Named constructor idiom, as one example.

 

class Shape
{
     Shape(); //Default constructor.
     Shape(VertexArray vertices); //Create a shape from a list of points.
 
     static Shape CreateRectangle(x, y, width, height); //Convenience function to create and return a shape.
};
 
Shape shape(......);
Shape myRectangle = Shape::CreateRectangle(x, y, width, height);

 

In my own code-base oftentimes I have static member variables that are shared by every instance of that class (for example, "DefaultTileImage" of a Tile class).

Due to API requirements, I can't load images until after the API has been initialized and a window created, so I can't initialize and load DefaultTileImage in the source file:

Image Tile::DefaultTileImage = NULL; //I can't load it here, because of the API requirements.

 

So instead, I have a static function to load the Tile's static DefaultTileImage, after the API has been initialized.

...API is initialized...
...game is being initialized...
Tile::LoadDefaultTileImage("image");

Edited by Servant of the Lord, 31 March 2013 - 01:37 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#4 AllEightUp   Moderators   -  Reputation: 4241

Like
1Likes
Like

Posted 31 March 2013 - 01:46 PM

Another case which I was just reviewing is differentiation of action.  Take for example the normalize function in a vector3 class:

 

class vector3
{
public:
   void     Normalize();  // Normalize "this" vector without return.  Folks will be annoyed..
   // or
   vector3 Normalize() const;  // Normalize the vector and return it, not modifying "this".
   // or a poorly written library could have the above and this next one at the same time:
   vector3& Normalize(); // Normalize "this" vector and return a reference.
   // Ack, same usage completely different meaning, which gets called?  Probably the compiler would bitch
   // since it doesn't know which to call in some cases.
};

 

So with a static function you could get both behaviors in an explicit manner:

 
class vector3
{
public:
   vector3&     Normalize();  // Normalize "this" vector.
   static vector3 Normalize( const vector3& );
};
 
From the signatures there is pretty much no way you can read those incorrectly or expect the behavior to be different than it is.  Not suggesting this is a great answer for a vector, I was just thinking about this recently as mentioned and this was a use/case.


#5 TheChubu   Crossbones+   -  Reputation: 4588

Like
1Likes
Like

Posted 31 March 2013 - 01:54 PM

There is the static factory pattern. And my math library (and some utilities) are made out of static methods too.

 

A cross product isn't something inherent of an object. So my static math class deals with that (and a whole other bunch of operations).


Edited by TheChubu, 31 March 2013 - 01:56 PM.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

 

My journals: dustArtemis ECS framework and Making a Terrain Generator


#6 MichaelNIII   Members   -  Reputation: 195

Like
0Likes
Like

Posted 31 March 2013 - 03:19 PM

I'm not sure if its right but my input class requires static functions to do calls from a pointers. I have it set up so that persay W calls the function address stored and that just happens to be my static cameras class "move forward" function.

#7 Servant of the Lord   Crossbones+   -  Reputation: 20384

Like
1Likes
Like

Posted 31 March 2013 - 04:04 PM

Another case which I was just reviewing is differentiation of action.

Excellent example!

So with a static function you could get both behaviors in an explicit manner:

 
class vector3
{
public:
   vector3&     Normalize();  // Normalize "this" vector.
   static vector3 Normalize( const vector3& );
};
 
From the signatures there is pretty much no way you can read those incorrectly or expect the behavior to be different than it is.  Not suggesting this is a great answer for a vector, I was just thinking about this recently as mentioned and this was a use/case.


Some people try to distinguish them by their names as well. 'Normalize' (normalizes 'this'), 'Normalized' (returns a copy that is normalized). The benefit is that you see the difference when reading the function when in use, and not just when reading the function definition.
vecA.Normalize(); //Unknown whether this is returning or not.
vs:
Vector vecB = vecA.Normalized(); //Definitely returning.
Typically I just have my codebase always operate on 'this' and copy explicitely, but that's just by habit - not by consciously thinking it through - but I figure I'd throw out the naming difference as an idea that others sometimes use. I started a thread inquiring about this a year ago, which might be interesting.

Also note that with static vs non-static similarly named functions, you have to be aware of an unintuitive C++ feature: You can call static functions from a class instance.
myInstance.StaticFunction(27, "blah");
I always call my static functions using the class scope explicitly (even if called from within other class functions), as there is zero ambiguity in that method:
int result = MyClass::StaticFunction(27, "blah");

Edited by Servant of the Lord, 31 March 2013 - 04:24 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]


#8 irreversible   Crossbones+   -  Reputation: 1383

Like
0Likes
Like

Posted 31 March 2013 - 11:52 PM

I generally use them for user callbacks:

 

 

 
class IWindow
{
public:
  //pass in ptr to object as we no longer have access to it directly
  static int OnMouse(int, int, int, IWindow*);
};
 
IWindow* w = new IWindow;
w->OnMouse = MyMouseProc;

Edited by irreversible, 31 March 2013 - 11:53 PM.


#9 Juliean   GDNet+   -  Reputation: 2696

Like
0Likes
Like

Posted 01 April 2013 - 01:26 AM

If you want to implement sort of an auto increment type id (here called family):

 

#pragma once

struct BaseComponent
{
    typedef unsigned int Family;

protected:
    static Family family_count;
};

template <typename Derived>
struct Component : public BaseComponent {
    static Family family(void);
};

template<typename C>
unsigned int Component<C>::family(void) {
    static BaseComponent::Family Family = family_count++;
    return Family;
}

//"always" = if first called in that order
class Derived : public Component<Derived> {};
Derived::family(); // always 0
class Derived2 : public Component<Derived2> {};
Derived2::family(); //always 1 

Edited by The King2, 01 April 2013 - 01:28 AM.


#10 Paradigm Shifter   Crossbones+   -  Reputation: 5413

Like
0Likes
Like

Posted 01 April 2013 - 02:32 AM

I generally use them for user callbacks:

 

 

 
class IWindow
{
public:
  //pass in ptr to object as we no longer have access to it directly
  static int OnMouse(int, int, int, IWindow*);
};
 
IWindow* w = new IWindow;
w->OnMouse = MyMouseProc;

 

 

That's not going to compile... you'd need to declare the functions pointer as

 

static int (*OnMouse)(int, int, int, IWindow*);

 

and you can use pointer to member functions for that anyway

 

If you want to implement sort of an auto increment type id (here called family):

 

#pragma once

struct BaseComponent
{
    typedef unsigned int Family;

protected:
    static Family family_count;
};

template <typename Derived>
struct Component : public BaseComponent {
    static Family family(void);
};

template<typename C>
unsigned int Component<C>::family(void) {
    static BaseComponent::Family Family = family_count++;
    return Family;
}

//"always" = if first called in that order
class Derived : public Component<Derived> {};
Derived::family(); // always 0
class Derived2 : public Component<Derived2> {};
Derived2::family(); //always 1 

And I'm not sure that will compile either since you can't call a function outside of a function body unless it is as an initializer for a global or static object... unless that's new in C++11


"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#11 Juliean   GDNet+   -  Reputation: 2696

Like
0Likes
Like

Posted 01 April 2013 - 03:27 AM

And I'm not sure that will compile either since you can't call a function outside of a function body unless it is as an initializer for a global or static object... unless that's new in C++11

 

This does indeed compile, at least with the inofficial VS november 2012 compiler with extended c++11 support. Didn't know about that restriction though, but might really be c++11.



#12 Ameise   Members   -  Reputation: 754

Like
0Likes
Like

Posted 04 April 2013 - 01:54 PM

And I'm not sure that will compile either since you can't call a function outside of a function body unless it is as an initializer for a global or static object... unless that's new in C++11

 

This does indeed compile, at least with the inofficial VS november 2012 compiler with extended c++11 support. Didn't know about that restriction though, but might really be c++11.

 

Doesn't compile in GCC:

http://ideone.com/AWMOUV



#13 Juliean   GDNet+   -  Reputation: 2696

Like
0Likes
Like

Posted 04 April 2013 - 02:16 PM

Doesn't compile in GCC:

http://ideone.com/AWMOUV

 

I was talking about my code, the second half of paradigm shifter's post with the confusing "family" naming convections ;)


Edited by The King2, 04 April 2013 - 02:16 PM.


#14 Vlad86   Members   -  Reputation: 130

Like
0Likes
Like

Posted 04 April 2013 - 08:43 PM

If you declare global static object in c/cpp file "static type gObjectName;" you cannot link the object from the header file by calling "extern type gObjectName;".



#15 Cornstalks   Crossbones+   -  Reputation: 6991

Like
0Likes
Like

Posted 04 April 2013 - 11:21 PM

If you declare global static object in c/cpp file "static type gObjectName;" you cannot link the object from the header file by calling "extern type gObjectName;".

Good example of static, bad example of a static *member* function :)

I just wrote a static method in my Matrix class. The static identity() member function returns the identity matrix.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS