neural.atlant
neural.atlant

Reputation: 225

Definition of function which is the class member

I have two functions, which are private members of class "Data":

class Date
{
private:
    bool leapYear(int y);
    void fillDate(int d, Month m, int y);
};

So, where is the best to define this functions:

Upvotes: 4

Views: 110

Answers (3)

Alexandre C.
Alexandre C.

Reputation: 56986

You have the choice here. Here are some ideas to make your mind:

  • Inlining for speed is no longer a concern, since compilers are now good at link time optimization. So performance should not be a decision factor here (compilation speed matters too, but this is another bag of worms).
  • Small inline member functions, defined inside the class, may be an easy way to "document" what the class does. Also, this tends to keep the implementation localized, which is comfortable when reading the code. Don't overdo it however.
  • Large functions should in principle go into their own file, or at least outside the class definition, since they clutter the class definition code for no good reason. Template code is no exception.
  • Pimpl have advantages/disadvantages too, but here I don't see any good reason to introduce such beasts in your simple case. They are used typically to reduce dependencies between header files.

Here, if the implementation is small, you can write the code inline, inside the class. But you should put them in their own implementation (".cpp") file, if the logic is complex.

You can also start inline, and when the code has settled to something more complex, move the implementation to its own file.

Upvotes: 4

Maged Elghareib
Maged Elghareib

Reputation: 119

I strongly discourage you to consider option 2. This gets you "Multiple definition" error by the linker if you include this file in more than one implementation file, because the definition will be copied (by the preprocessor) to each .cpp file.

Upvotes: 1

Peter Goldsborough
Peter Goldsborough

Reputation: 1388

My personal philosophy about this is to put all function definitions into the implementation (.cpp) file, because, first of all, it separates declarations (+ documentation) from definitions which adds to code clarity IMO, and, secondly, having all definitions in one place (the implementation file) makes it easier for me to find functions. In my experience it was always quite a nuisance to have to switch between header and implementation files to see whether this particular function I'm looking for was inlined / defined in the header or if it was in the implementation file. Having all function definitions in the implementation file means I know I will find the definition of any function in that file, and won't have to waste time switching and looking around.

Upvotes: 0

Related Questions