Defining member functions of a class? - c++

I am working with a book on c++ and to solve the problems I am always asked to declare the member functions' prototypes in the xxxxxx.h file and define the functions body properly in the xxxxxx.cpp file. Is there any harm or disadvantage in defining the member functions in the .h file? If not, is there any benefit or advantage in defining them in the .cpp file?

If you will always write your code in .h files you will never be able to performa some technics, such as forward declaration. Since you can't use forward declaration if writing code in headers you will be not able to solve cross dependencies.
So you will need to include everything you need in .h file. Including this file in other file will include everything already included. Thus any small change in you code will result in almost full recompilation in many cases.
Also it's harder to read the code in .h files because you expect to see the interface of the class in .h, not implementation.

If you define the method in the header, you have to mark it as inline or define them inside the class definition to prevent multiple definitions:
//A.h
class A
{
void f()
{
}
void g();
};
inline void A::g()
{
};
Other than that, it's a matter of coding style. You generally keep your headers clean, as to only provide an interface to work with the class, and abstract away the implementation details.
Generally. There are cases where you have to define the functions in the header (templates) or when you want to (to allow better compiler optimizations).

Related

Is it okay to provide the definition of a constructor inside the header file that declares it?

I am fairly new to C++, and I am sorry if this has been asked before but I did find a relevant answer. I know that it is poor practice to define methods inside header files, unless they are class templates in which they has to be defined inside the header file. How about for constructors? For example, I define empty constructors in .h files like so:
bmd2FileException(const std::string & _description) throw() : bmd2Exception(_description) {}
I also have an overloaded constructor which has a non-empty definition:
bmd2FileException(const std::string & _description, const char *, long int) throw() {
// do stuff
}
Do I need to include a seperate .cpp file for one or the other, or both constructors?
Thank you!
Yes, you can define constructors in the header file, typically inside the class definition itself as you have been doing.
No, it isn't necessarily poor practice. For example, it is probably silly to create a cpp file just to put the constructor definition somewhere other than the header, if the constructor is short and simple.
Edit: What you mention in your comments section about compiler errors about multiple definitions of the same function is true, but the situation where you define a class member method in the class definition is an exception.
Generally, your .h file is an interface file which means it just shows the methods you have but doesn't actually implement them. If you do want to do a .h and a .cpp file for one of your classes, you should probably implement your methods in your .cpp file instead of your .h file, as that is what the files were intended to be used for.
One reason you may not be able to implement functions in your constructors is that if two files need to include each other, you cannot have implementations in the headers.

How to make a template function in test.h use a static method inside test.cpp

Currently the template functions are inside the .cpp file, however these templates need to be defined in the header. However, when I move them in to the header, the templates have no access to the static methods inside the .cpp file. What changes do I need for this to work?
This is just a utility header and cpp, nothing to do with classes.
I would just go ahead and put declarations of all needed functions in a header file (and remove the static from their definitions). If you put them in namespace FunctionName_impl_detail or something like that, you're safe from name collisions. If you put comments near the declarations discouraging using them directly, you probably don't need to "hide" or "protect" them. But if you want to mostly prevent other code from using them, you can make them private, static members of some class which friends the template functions.
You should define the static method in the header.
Template classes have to be defined entirely in the header file because the compiler basically creates a new class for each template instantiation, so it has to have access to the full method implementation at compilation time.

Where should support function declarations go?

I have a .cpp source file with some functions that need to be publicly accessible and some support functions that are only used in this source file.
I have been putting the all of these functions declarations in the header file as I personally find it useful to see everything a class offers in one place. However I would like to indicate whether the functions are for internal use, similar to the private access modifier, but without using classes (they are standalone functions).
Some possible solutions are:
Put the private declarations in the source file.
Put the private declarations in a separate header.
Both of these solutions split the public and private functions into separate files which I would like to avoid.
If the functions are not intended for public use, the shouldn't be placed into the header. Put them into the source file they are used in.
To completely hide these functions from being used outside the source file one of the following is usually done:
Functions are declared as static.
Functions are put into an unnamed namespace.
The latter is considered preferable. Actually, the C++ Standard 7.3.1.1 states:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.
For more discussion about unnamed namespaces vs static refer to Unnamed/anonymous namespaces vs. static functions and to corresponding comp.lang.c++.moderated thread.
If the private functions are only used in a single source file, then you don't need any extra header file. Just mark the functions either static or use an anonymous namespace.
If the functions can be used from many source files, declare them in a separate header file in a special namespace. That's my advice.
Where should support function declarations go?
They don't have to go anywhere. Make them static and keep them in source file. If they're only used in single source file, there's no need to put forward declarations into any header.
You don't mention whether these 'functions' are members of a class but I'll assume that they are. If so, I would recommend that you look at the 'pimpl idiom'. Basically this means putting all or most of what you want to keep private into a seperate class and then only having a pointer to an instance of the class in your class declaration. For example:
class MyClass
{
// ... some stuff
private:
SecretObject obj_;
int hiddenCall();
};
becomes
class MyClassImpl;
class MyClass
{
private:
MyClassImpl* impl_;
};
The idea then is that all the declaration and definition of your implemntation class would go into your .cpp file which hides it from anything but the compilation unit. This approach has a number of important advantages:
Hides implementation so the publicly available header does not give too much of the implementation away.
Can increase compilation speed by removing dependecies in the header - v. important if the header is included a lot.
Can be useful for 'insulating` client code against libraries that they shouldn't need to build against such as database APIs etc.
There are a number of drawbacks:
Can make unit testing more tricky if code is hidden away in cpp files. Personally I find a better solution is to have a seperate, private header and implementation file so you can control what clients of your code get but a test harness can still test it adequately. You can simply include the MyClassImpl header in your cpp file, but don't include it in the MyClass header - this would defeat the object.
The indirection between MyClass and MyClassImpl can be tiresome to code / manage.
Generally though, it's probably the best way of acheiving what you want to get to. Look at articles by Herb Sutter for a more in depth explaination.
On the other hand, if you are talking about free functions, not directly related to the class, then I would put these within the unnamed namespace within your cpp file. For example:
namespace {
// Your stuff goes here.
};
Again, you've got a unit test issue of how to access these functions if you take this approach, but it's possible to work around this if that's really an issue, perhaps by creating a specific namespace, conditional compilation etc. Not ideal, but possible.

Should accessors be Inlined?

This is the declaration in the header file:
class PrimeSieve
{
populate(int lim);
vector<int> sieve;
long long limit;
public:
unsigned int limit();
};
Should I define the accessor method in the .cpp file or in the .h, inline?
I'm new to C++, but I'd like to follow best practices. I've seen this around in some of the books—is this considered standard?
unsigned int limit() { return limit; };
Definitely write the accessor inline in the header file. It makes better optimizations possible, and doesn't reduce encapsulation (since changes to the format of private data require recompiling all units that include the header anyway).
In the case of a complicated algorithm, you might want to hide the definition in an implementation file. Or when the implementation requires some types/header files not otherwise required by the class definition. Neither of those cases applies to simple accessors.
For one-liners, put it inside the class definition. Slightly longer member functions should still be in the header file, but might be declared explicitly inline, following the class definition.
Most newer compilers are smart enough to inline what is necessary and leave everything else alone. So let the compiler do what its good at and don't try to second guess it.
Put all your code in the .cpp and the code declarations in the .h.
A good rule of thumb is to put all your code in the .cpp file, so this would argue against an inline function in the .h file.
For simple data types in classes fully visible to clients of the class, there is no real difference as you need to recompile the client whenever the class definition changes.
The main reason to make an accessor rather than use the member directly is to allow the implementation to remove the data member later on and still keep the interface compatible; if the interface containing the accessor is unchanged, the result is typically binary compatible, otherwise, it's source compatible. Having the accessor inline means defining it as part of the interface that you are changing, so you can ever only be source compatible.
The other reason to have an accessor is a DLL boundary: If your accessor needs to call into another function, and you allow it to be inlined, then this function's symbol needs to be exported to the client as well.
Depending on the complexity of the project, it can be beneficial to define an interface for your code as an abstract class, which allows you to change the implementation to your heart's content without the client ever seeing the change; in this case, accessors are defined as abstract in the interface class and clients cannot inline them, ever.
The argument for declaring the accessor inline is that this eliminates the call over-head, and can enable some further optimisations.
My experienced of measured performance is that the gain from doing this is usually rather modest. I consequently no longer do it by default.
More than being kind of global programming standards, these vary from organizations to organizaions. Of course, getLimit() would still be better than mere limit().

Member function definition

What is the right approach to take:
Define the member (class) function inside the class?
Define the member (class) function outside the class?
Thanks.
Assuming you're talking about these three possibilities:
Method defined in class definition in header file.
Method define outside class definition in header file.
Method define outside class definition in implementation file.
Then project and company guidelines may force you to use (1) or (3) always.
When you have a choice, it's IMHO best to adapt to circumstances at hand, considering things such as
Do you want a header-only module? Then (1) as default, (2) possible.
Is the method a large beast? Then (2) or (3).
Template method specialization? Then (2) or (3).
There is a build-time problem (slow builds)? Indicates (3).
Template class? (1) or possibly (2)
But except where the choice is effectively forced on you, above all consider the clarity of your code.
Cheers & hth.,
A common advice is to keep headers as simple and clean as possible. Headers will be included by external code, and they will have to process everything that you have written there. If you write a method in the header, all translation units will compile that function, only so that the linker can discard all but one of them later on.
If your code has an internal dependency on a type or library that is not part of your interface, then by inlining the code of the member function in the class declaration the definition of that class or the headers of that library will have to be included in your header, and that means that you are leaking your implementation details to your users.
Unless the member function definition is trivial (in an informal sense) and doesn't introduce any additional dependencies I would normally define a member function outside of the class body in a separate source file.
It's often a matter of style but there are some cases in which it is necessary and many other cases in which it is desirable to define function outside of the class body.
For example, in the cases where you have interdependent classes and only a forward declaration of another class can be made available before the class definition, a member function which uses the definition of that other class can only be defined outside of the class body after a full definition of the other class has been provided.
Do you mean "in the class declaration / .h file" vs "in a .cpp file using ::" ?
If so I always go for the latter. When it comes to debugging, it's a lot easier to step through and see what's going on. It also helps declutter the class declaration, which doesn't need to know any implementation details"
If you want to define a function within a class the most basic syntax looks generally like:
class Object
{
int property;
void doSomething()
{
property=100;
}
};
If you want to define a function outside it is similar to declaring functions before main and in library files. In your class you have:
class Object
{
int property;
void doSomething();
};
Then somewhere after your class, after the main() function or in an included file you can have the definition:
void Object::doSomething()
{
property=100;
}
Some place classes in a header file and the definitions in a cpp file used by that header. Various techniques possible.
Both of these approaches are valid. Often I will include very small and/or core class functionality directly within the class and other functions which do heavier bulk work I tend to separate. Try to think the difference in coming upon your code and wanting to alter it.
if we see according to performance issue than it is more effective way to declare the function in the class . becouse at the compile time it conects all the funcation calls and other components so it will easy and must be faster to get all in one source...