0

What is the normal practice when it comes to non-member function in C++? Do we put them in main.cpp or header file or class implementation file, or do we make a separate .cpp file for it? If the normal practice is to make a separate file, then where do we put the non-member function header(prototype)? Does it only go in main.cpp or in both of them?

donjuedo
  • 2,395
  • 14
  • 26
juice009
  • 3
  • 5
  • Well if you ask me the only function in main.cpp should be main. And perhaps some helper functions. – DeiDei May 03 '17 at 00:11

3 Answers3

4

I would say you should not treat non-member functions differently to classes and member functions and other symbols.

You should create a distinct header file .h and a corresponding source file .cpp for each logical component (module) of your application.

All public symbols should be declared/defined in the header file (whether they be non-member functions or otherwise) and all non-public symbols and all required definitions should go in the source file.

In short, group according to logical program components, rather than by the type of symbol/function.

Galik
  • 42,526
  • 3
  • 76
  • 100
0

Your class should have its own .cpp file. Non-member functions should go in other files (all together or grouped according to similarity). That's the convention here in North America, but conventions differ. Prototype just needs go into header file so you can include it wherever you use it.

Fuad
  • 1,187
  • 1
  • 12
  • 30
  • Does the non-member function go in main function cpp file or do we create a .cpp for itself only. – juice009 May 03 '17 at 00:03
  • either is okay. If you have many non-member functions, you should put them in a separate file, and include it in the main .cpp file. – Fuad May 03 '17 at 00:23
0

General idea in pseudo code:

if (it will be used in other cpp files) 
    put the declaration in a header file. 
    implement it in a header or a cpp file.
else 
    if (only need it in some functions in a header file)
        if (it's a function more than N line )  // please define this N in your mind
            declare it in the same header and implement it in a cpp file
        else
             put it in the same header file
    else // used in cpp only
        put it in the cpp file

As long as it compiles, you should consider readability (easy for anyone to read) and accessibility (easy for anyone to find and debug).

laishiekai
  • 741
  • 8
  • 24