Implementation of member functions

Asked

Viewed 46 times

0

It was overloading operators and defining them within the class itself, I found it natural to do so for these functions, but then a small doubt arose.

Is it wrong to define member functions within the class itself? Or is it just a matter of code organization to write the prototypes in the class creation and then implement them?

2 answers

0


It is not wrong if it is desired. The definition outside exists for some reasons, some more important than others, mainly:

  • Separate compilation does not require everything to go through the analysis process every time you process the class declaration where the necessary contracts where you consume the class are located and you gain time. This is worth less for newer versions of C++ that have modules.
  • It is possible to make some composition of different implementations keeping the same contract, which should be done sparingly and very carefully. Most languages don’t allow this. C++ is flexible and powerful, it even lets you shoot yourself in the foot if you don’t handle the right gun.

So it’s to organize, but for a technical reason and not because it looks cute.

There are cases that you are (or were) required to define the implementation next to the statement when you want certain types of optimization, typical of operators and many simple functions and because that is part of a class gauge and only with the source together with the concrete type instance needs all the source.

0

Is it wrong to define member functions within the class itself? Or is it just a matter of code organization to write the prototypes in the class creation and then implement them?

In general it is wrong even.

When it makes sense?

  • when you use templates
  • when it is a class of constants only
  • in very simple programs, such as student programs, in which classes are often defined and main() and all in a single source file

Imagine the case of the class vector, class list. Of iostream. These classes redefine several operators for example. And it has many constructs and complex implementation. And you don’t compile it all the time. Only the library is used

If the implementation is all in the header anyone who uses the class will read the implementation and it’s almost never what you want. The implementation may not have been sold, but only the functionality. A lot of people write classes as a source of income ;)

If you have a separate header plus the complete file will have to keep twice the same thing, and this is a risk

If you have multiple implementations of the same class in general you will want to keep a single header with the prototypes for your own safety. And test the implementations in various scenarios knowing that the prototypes and structures are the same

Browser other questions tagged

You are not signed in. Login or sign up in order to post.