Thread: global functions and OO

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    630

    global functions and OO

    Hello

    I never want to have any global functions, instead I always try to put them somewhere..

    Im unsure if I should put global functions inside namespace, struct or class (as static functions).

    For instance:
    Lets say I have int my_random() function, that returns random number.

    Should I put it inside a namespace or struct/class?

    I noticed most of OO programers would do:

    Code:
    namespace various {
      int my_random() { }
    }
    So what is the best approach?

  2. #2
    Registered User
    Join Date
    May 2007
    Posts
    88
    From a design standpoint, it doesn't make sense to add a method to a class that doesn't have anything to do with that particular class. So yes, I would say the best approach is to add that function to a namespace with other various utilities, if you're really that concerned about it.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I would put such free functions inside a suitable namespace, since that is what namespaces are for.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. First time doing OO
    By Kross7 in forum C++ Programming
    Replies: 9
    Last Post: 05-11-2007, 12:55 PM
  2. Simple OO Problem
    By bstempi in forum C++ Programming
    Replies: 1
    Last Post: 04-30-2004, 05:33 PM
  3. My first OO C++ app
    By CompiledMonkey in forum C++ Programming
    Replies: 16
    Last Post: 12-20-2003, 04:36 AM
  4. functions defined as a string
    By river-wind in forum C Programming
    Replies: 2
    Last Post: 11-21-2001, 10:36 AM