Should I use static functions?

I'm trying to figure out which of the following options is the best way. In a library like GLM, you have functions like glm::perspective(). I didn't have to instantiate anything to call it, so I'm guessing it's a static function?

If I wanted to do something similar to GLM, would I have to go for option 1?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // Option 1
  static Mat4 Translate(float x, float y, float z) { return translate; }
 
   // or 

   class Mat4 {
   public:
    // Option 2
      Mat4 Translate(float x, float y, float z) { return translate; }
   };

   // Main.cpp

   // Option 1
   Mat4 r = Maths::Translate(0,0,0);
   
    // Option 2
   Mat4 r;
   r = r.Translate(0,0,0);


No static functions in option 2, but I did have to create a Mat4 object.
Last edited on
The name "Translate" suggests that the function does something based on its this parameter. If so, it should be non-static. If it only creates a translation matrix, it should be static and renamed to something like "CreateTranslationMatrix" or "CreateTranslation".
> In a library like GLM, you have functions like glm::perspective().
> I didn't have to instantiate anything to call it, so I'm guessing it's a static function?

No, it is a non-member function; glm is the namespace in which the function perspective resides.


> I'm trying to figure out which of the following options is the best way.

If you're writing a function that can be implemented as either a member or as a non-friend non-member, you should prefer to implement it as a non-member function. That decision increases class encapsulation. When you think encapsulation, you should think non-member functions. - Scott Meyers in Dr. Dobb's

http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197?

Assuming that Translate returns the result of applying a tranformation to a Mat4 object, somethng like this:
1
2
3
4
5
6
namespace maths
{
    class Mat4 ;
    
    Mat4 Translate( const MAT4& m, double x, double y, double z ) ;
};

Thanks guys, helped a lot. I really thought glm::perspective was a static function. Now I know about non-member functions.
Topic archived. No new replies allowed.