0

Hi i'm fairly new to c++ and i'm facing a bit of an issue when it comes to coding classes.

While i understand that every functions that is related to the class should be a member function of that class.

i'm unsure what to do with simple function that don't really belong to any class. such as a help message. they're not related to any object so where do i put them? in there own class called misc or utility or something along those lines? or do i just place them in a class that is "sorta" related?

louise
  • 5
  • 1
  • 1
    Probably a duplicate: https://stackoverflow.com/q/8226489/1531971 –  May 01 '18 at 17:25
  • 2
    Possible duplicate of [Organising utility functions in C++](https://stackoverflow.com/questions/8226489/organising-utility-functions-in-c) – Johan May 01 '18 at 17:30
  • Side note: [Some functions that seem like member functions actually should not be](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-member). If a function makes no use of private data, consider making it a free function. – user4581301 May 01 '18 at 17:51

2 Answers2

1

functions which do not belong to any class just place them outside the main() and any class. you can also make a separate .cpp and .h file (.h for declaration and .cpp for function definition) to write all the functions and then include it in your main file.

Asim Sansi
  • 39
  • 8
0

1) If it's a large project, I would group similar ones together and put them in files such as misc.h you recommended. To prevent confusion, you could either put them as static member functions of a class, or simpler put them in a namespace:

misc.h

#include <iostream>
namespace misc {
    void print(char *s) { std::cout << s << std::endl; }
}
// OR
class misc {
public:
    static void print(char *s) { std::cout << s << std::endl; }
};
// static here allows calling the function without an object of type misc.

main.cpp

#include "misc.h"
int main() { misc::print("Hello, World"); } 

2) If it's a small project I wouldn't worry too much. I'd put them over the main function.

3) If they are helper functions for the implementation of one of your classes I highly recommend declaring them as static in your implementation files. This prevents linking with other files.

This would look like this:

A.cpp:

static int print(char *s) { std::cout << s << std::endl; }

A::A() { print("Constructed"); }
Kostas
  • 4,061
  • 1
  • 14
  • 32
  • 1
    Side note: If you have compiler support for anonymous namespaces, strongly consider [using them in place of `static`](https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static). – user4581301 May 01 '18 at 17:55